repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/DocumentationComments/DocumentationCommentSnippet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.DocumentationComments
{
internal class DocumentationCommentSnippet
{
/// <summary>
/// The span in the original text that should be replaced with the documentation comment.
/// </summary>
public TextSpan SpanToReplace { get; }
/// <summary>
/// The documentation comment text to replace the span with
/// </summary>
public string SnippetText { get; }
/// <summary>
/// The offset within <see cref="SnippetText"/> where the caret should be positioned after replacement
/// </summary>
public int CaretOffset { get; }
internal DocumentationCommentSnippet(TextSpan spanToReplace, string snippetText, int caretOffset)
{
SpanToReplace = spanToReplace;
SnippetText = snippetText;
CaretOffset = caretOffset;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.DocumentationComments
{
internal class DocumentationCommentSnippet
{
/// <summary>
/// The span in the original text that should be replaced with the documentation comment.
/// </summary>
public TextSpan SpanToReplace { get; }
/// <summary>
/// The documentation comment text to replace the span with
/// </summary>
public string SnippetText { get; }
/// <summary>
/// The offset within <see cref="SnippetText"/> where the caret should be positioned after replacement
/// </summary>
public int CaretOffset { get; }
internal DocumentationCommentSnippet(TextSpan spanToReplace, string snippetText, int caretOffset)
{
SpanToReplace = spanToReplace;
SnippetText = snippetText;
CaretOffset = caretOffset;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/ColorSchemes/ColorSchemeApplier.Settings.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Editor.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NativeMethods = Microsoft.CodeAnalysis.Editor.Wpf.Utilities.NativeMethods;
namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes
{
internal partial class ColorSchemeApplier
{
private class ColorSchemeSettings
{
private const string ColorSchemeApplierKey = @"Roslyn\ColorSchemeApplier";
private const string AppliedColorSchemeName = "AppliedColorScheme";
private readonly IServiceProvider _serviceProvider;
private readonly IGlobalOptionService _globalOptions;
public ColorSchemeSettings(IServiceProvider serviceProvider, IGlobalOptionService globalOptions)
{
_serviceProvider = serviceProvider;
_globalOptions = globalOptions;
}
public ImmutableDictionary<SchemeName, ColorScheme> GetColorSchemes()
{
return new[]
{
SchemeName.VisualStudio2019,
SchemeName.VisualStudio2017
}.ToImmutableDictionary(name => name, name => GetColorScheme(name));
}
private ColorScheme GetColorScheme(SchemeName schemeName)
{
using var colorSchemeStream = GetColorSchemeXmlStream(schemeName);
return ColorSchemeReader.ReadColorScheme(colorSchemeStream);
}
private Stream GetColorSchemeXmlStream(SchemeName schemeName)
{
var assembly = Assembly.GetExecutingAssembly();
return assembly.GetManifestResourceStream($"Microsoft.VisualStudio.LanguageServices.ColorSchemes.{schemeName}.xml");
}
public void ApplyColorScheme(SchemeName schemeName, ImmutableArray<RegistryItem> registryItems)
{
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: true);
foreach (var item in registryItems)
{
using var itemKey = registryRoot.CreateSubKey(item.SectionName);
itemKey.SetValue(item.ValueName, item.ValueData);
// Flush RegistryKeys out of paranoia
itemKey.Flush();
}
registryRoot.Flush();
SetAppliedColorScheme(schemeName);
// Broadcast that system color settings have changed to force the ColorThemeService to reload colors.
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SYSCOLORCHANGE, wparam: IntPtr.Zero, lparam: IntPtr.Zero);
}
/// <summary>
/// Get the color scheme that is applied to the configuration registry.
/// </summary>
public SchemeName GetAppliedColorScheme()
{
// The applied color scheme is stored in the configuration registry with the color theme information because
// when the hive gets rebuilt during upgrades, we need to reapply the color scheme information.
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: false);
using var itemKey = registryRoot.OpenSubKey(ColorSchemeApplierKey);
return itemKey is object
? (SchemeName)itemKey.GetValue(AppliedColorSchemeName)
: default;
}
private void SetAppliedColorScheme(SchemeName schemeName)
{
// The applied color scheme is stored in the configuration registry with the color theme information because
// when the hive gets rebuilt during upgrades, we need to reapply the color scheme information.
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: true);
using var itemKey = registryRoot.CreateSubKey(ColorSchemeApplierKey);
itemKey.SetValue(AppliedColorSchemeName, (int)schemeName);
// Flush RegistryKeys out of paranoia
itemKey.Flush();
}
public SchemeName GetConfiguredColorScheme()
{
var schemeName = _globalOptions.GetOption(ColorSchemeOptions.ColorScheme);
return schemeName != SchemeName.None
? schemeName
: ColorSchemeOptions.ColorScheme.DefaultValue;
}
public void MigrateToColorSchemeSetting()
{
// Get the preview feature flag value.
var useEnhancedColorsSetting = _globalOptions.GetOption(ColorSchemeOptions.LegacyUseEnhancedColors);
// Return if we have already migrated.
if (useEnhancedColorsSetting == ColorSchemeOptions.UseEnhancedColors.Migrated)
{
return;
}
var colorScheme = useEnhancedColorsSetting == ColorSchemeOptions.UseEnhancedColors.DoNotUse
? SchemeName.VisualStudio2017
: SchemeName.VisualStudio2019;
_globalOptions.SetGlobalOption(new OptionKey(ColorSchemeOptions.ColorScheme), colorScheme);
_globalOptions.SetGlobalOption(new OptionKey(ColorSchemeOptions.LegacyUseEnhancedColors), ColorSchemeOptions.UseEnhancedColors.Migrated);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Editor.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NativeMethods = Microsoft.CodeAnalysis.Editor.Wpf.Utilities.NativeMethods;
namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes
{
internal partial class ColorSchemeApplier
{
private class ColorSchemeSettings
{
private const string ColorSchemeApplierKey = @"Roslyn\ColorSchemeApplier";
private const string AppliedColorSchemeName = "AppliedColorScheme";
private readonly IServiceProvider _serviceProvider;
private readonly IGlobalOptionService _globalOptions;
public ColorSchemeSettings(IServiceProvider serviceProvider, IGlobalOptionService globalOptions)
{
_serviceProvider = serviceProvider;
_globalOptions = globalOptions;
}
public ImmutableDictionary<SchemeName, ColorScheme> GetColorSchemes()
{
return new[]
{
SchemeName.VisualStudio2019,
SchemeName.VisualStudio2017
}.ToImmutableDictionary(name => name, name => GetColorScheme(name));
}
private ColorScheme GetColorScheme(SchemeName schemeName)
{
using var colorSchemeStream = GetColorSchemeXmlStream(schemeName);
return ColorSchemeReader.ReadColorScheme(colorSchemeStream);
}
private Stream GetColorSchemeXmlStream(SchemeName schemeName)
{
var assembly = Assembly.GetExecutingAssembly();
return assembly.GetManifestResourceStream($"Microsoft.VisualStudio.LanguageServices.ColorSchemes.{schemeName}.xml");
}
public void ApplyColorScheme(SchemeName schemeName, ImmutableArray<RegistryItem> registryItems)
{
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: true);
foreach (var item in registryItems)
{
using var itemKey = registryRoot.CreateSubKey(item.SectionName);
itemKey.SetValue(item.ValueName, item.ValueData);
// Flush RegistryKeys out of paranoia
itemKey.Flush();
}
registryRoot.Flush();
SetAppliedColorScheme(schemeName);
// Broadcast that system color settings have changed to force the ColorThemeService to reload colors.
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SYSCOLORCHANGE, wparam: IntPtr.Zero, lparam: IntPtr.Zero);
}
/// <summary>
/// Get the color scheme that is applied to the configuration registry.
/// </summary>
public SchemeName GetAppliedColorScheme()
{
// The applied color scheme is stored in the configuration registry with the color theme information because
// when the hive gets rebuilt during upgrades, we need to reapply the color scheme information.
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: false);
using var itemKey = registryRoot.OpenSubKey(ColorSchemeApplierKey);
return itemKey is object
? (SchemeName)itemKey.GetValue(AppliedColorSchemeName)
: default;
}
private void SetAppliedColorScheme(SchemeName schemeName)
{
// The applied color scheme is stored in the configuration registry with the color theme information because
// when the hive gets rebuilt during upgrades, we need to reapply the color scheme information.
using var registryRoot = VSRegistry.RegistryRoot(_serviceProvider, __VsLocalRegistryType.RegType_Configuration, writable: true);
using var itemKey = registryRoot.CreateSubKey(ColorSchemeApplierKey);
itemKey.SetValue(AppliedColorSchemeName, (int)schemeName);
// Flush RegistryKeys out of paranoia
itemKey.Flush();
}
public SchemeName GetConfiguredColorScheme()
{
var schemeName = _globalOptions.GetOption(ColorSchemeOptions.ColorScheme);
return schemeName != SchemeName.None
? schemeName
: ColorSchemeOptions.ColorScheme.DefaultValue;
}
public void MigrateToColorSchemeSetting()
{
// Get the preview feature flag value.
var useEnhancedColorsSetting = _globalOptions.GetOption(ColorSchemeOptions.LegacyUseEnhancedColors);
// Return if we have already migrated.
if (useEnhancedColorsSetting == ColorSchemeOptions.UseEnhancedColors.Migrated)
{
return;
}
var colorScheme = useEnhancedColorsSetting == ColorSchemeOptions.UseEnhancedColors.DoNotUse
? SchemeName.VisualStudio2017
: SchemeName.VisualStudio2019;
_globalOptions.SetGlobalOption(new OptionKey(ColorSchemeOptions.ColorScheme), colorScheme);
_globalOptions.SetGlobalOption(new OptionKey(ColorSchemeOptions.LegacyUseEnhancedColors), ColorSchemeOptions.UseEnhancedColors.Migrated);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/CodeAnalysisTest/InternalUtilities/StringExtensionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
namespace Roslyn.Utilities.UnitTests.InternalUtilities
{
public class StringExtensionsTests
{
[Fact]
public void GetNumeral1()
{
Assert.Equal("0", StringExtensions.GetNumeral(0));
Assert.Equal("5", StringExtensions.GetNumeral(5));
Assert.Equal("10", StringExtensions.GetNumeral(10));
Assert.Equal("10000000", StringExtensions.GetNumeral(10000000));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
namespace Roslyn.Utilities.UnitTests.InternalUtilities
{
public class StringExtensionsTests
{
[Fact]
public void GetNumeral1()
{
Assert.Equal("0", StringExtensions.GetNumeral(0));
Assert.Equal("5", StringExtensions.GetNumeral(5));
Assert.Equal("10", StringExtensions.GetNumeral(10));
Assert.Equal("10000000", StringExtensions.GetNumeral(10000000));
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/Portable/Text/TextSpan.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Immutable abstract representation of a span of text. For example, in an error diagnostic that reports a
/// location, it could come from a parsed string, text from a tool editor buffer, etc.
/// </summary>
[DataContract]
public readonly struct TextSpan : IEquatable<TextSpan>, IComparable<TextSpan>
{
/// <summary>
/// Creates a TextSpan instance beginning with the position Start and having the Length
/// specified with <paramref name="length" />.
/// </summary>
public TextSpan(int start, int length)
{
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start + length < start)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
Start = start;
Length = length;
}
/// <summary>
/// Start point of the span.
/// </summary>
[DataMember(Order = 0)]
public int Start { get; }
/// <summary>
/// End of the span.
/// </summary>
public int End => Start + Length;
/// <summary>
/// Length of the span.
/// </summary>
[DataMember(Order = 1)]
public int Length { get; }
/// <summary>
/// Determines whether or not the span is empty.
/// </summary>
public bool IsEmpty => this.Length == 0;
/// <summary>
/// Determines whether the position lies within the span.
/// </summary>
/// <param name="position">
/// The position to check.
/// </param>
/// <returns>
/// <c>true</c> if the position is greater than or equal to Start and strictly less
/// than End, otherwise <c>false</c>.
/// </returns>
public bool Contains(int position)
{
return unchecked((uint)(position - Start) < (uint)Length);
}
/// <summary>
/// Determines whether <paramref name="span"/> falls completely within this span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the specified span falls completely within this span, otherwise <c>false</c>.
/// </returns>
public bool Contains(TextSpan span)
{
return span.Start >= Start && span.End <= this.End;
}
/// <summary>
/// Determines whether <paramref name="span"/> overlaps this span. Two spans are considered to overlap
/// if they have positions in common and neither is empty. Empty spans do not overlap with any
/// other span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the spans overlap, otherwise <c>false</c>.
/// </returns>
public bool OverlapsWith(TextSpan span)
{
int overlapStart = Math.Max(Start, span.Start);
int overlapEnd = Math.Min(this.End, span.End);
return overlapStart < overlapEnd;
}
/// <summary>
/// Returns the overlap with the given span, or null if there is no overlap.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// The overlap of the spans, or null if the overlap is empty.
/// </returns>
public TextSpan? Overlap(TextSpan span)
{
int overlapStart = Math.Max(Start, span.Start);
int overlapEnd = Math.Min(this.End, span.End);
return overlapStart < overlapEnd
? TextSpan.FromBounds(overlapStart, overlapEnd)
: (TextSpan?)null;
}
/// <summary>
/// Determines whether <paramref name="span"/> intersects this span. Two spans are considered to
/// intersect if they have positions in common or the end of one span
/// coincides with the start of the other span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the spans intersect, otherwise <c>false</c>.
/// </returns>
public bool IntersectsWith(TextSpan span)
{
return span.Start <= this.End && span.End >= Start;
}
/// <summary>
/// Determines whether <paramref name="position"/> intersects this span.
/// A position is considered to intersect if it is between the start and
/// end positions (inclusive) of this span.
/// </summary>
/// <param name="position">
/// The position to check.
/// </param>
/// <returns>
/// <c>true</c> if the position intersects, otherwise <c>false</c>.
/// </returns>
public bool IntersectsWith(int position)
{
return unchecked((uint)(position - Start) <= (uint)Length);
}
/// <summary>
/// Returns the intersection with the given span, or null if there is no intersection.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// The intersection of the spans, or null if the intersection is empty.
/// </returns>
public TextSpan? Intersection(TextSpan span)
{
int intersectStart = Math.Max(Start, span.Start);
int intersectEnd = Math.Min(this.End, span.End);
return intersectStart <= intersectEnd
? TextSpan.FromBounds(intersectStart, intersectEnd)
: (TextSpan?)null;
}
/// <summary>
/// Creates a new <see cref="TextSpan"/> from <paramref name="start" /> and <paramref
/// name="end"/> positions as opposed to a position and length.
///
/// The returned TextSpan contains the range with <paramref name="start"/> inclusive,
/// and <paramref name="end"/> exclusive.
/// </summary>
public static TextSpan FromBounds(int start, int end)
{
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start), CodeAnalysisResources.StartMustNotBeNegative);
}
if (end < start)
{
throw new ArgumentOutOfRangeException(nameof(end), CodeAnalysisResources.EndMustNotBeLessThanStart);
}
return new TextSpan(start, end - start);
}
/// <summary>
/// Determines if two instances of <see cref="TextSpan"/> are the same.
/// </summary>
public static bool operator ==(TextSpan left, TextSpan right)
{
return left.Equals(right);
}
/// <summary>
/// Determines if two instances of <see cref="TextSpan"/> are different.
/// </summary>
public static bool operator !=(TextSpan left, TextSpan right)
{
return !left.Equals(right);
}
/// <summary>
/// Determines if current instance of <see cref="TextSpan"/> is equal to another.
/// </summary>
public bool Equals(TextSpan other)
{
return Start == other.Start && Length == other.Length;
}
/// <summary>
/// Determines if current instance of <see cref="TextSpan"/> is equal to another.
/// </summary>
public override bool Equals(object? obj)
{
return obj is TextSpan && Equals((TextSpan)obj);
}
/// <summary>
/// Produces a hash code for <see cref="TextSpan"/>.
/// </summary>
public override int GetHashCode()
{
return Hash.Combine(Start, Length);
}
/// <summary>
/// Provides a string representation for <see cref="TextSpan"/>.
/// </summary>
public override string ToString()
{
return $"[{Start}..{End})";
}
/// <summary>
/// Compares current instance of <see cref="TextSpan"/> with another.
/// </summary>
public int CompareTo(TextSpan other)
{
var diff = Start - other.Start;
if (diff != 0)
{
return diff;
}
return Length - other.Length;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Immutable abstract representation of a span of text. For example, in an error diagnostic that reports a
/// location, it could come from a parsed string, text from a tool editor buffer, etc.
/// </summary>
[DataContract]
public readonly struct TextSpan : IEquatable<TextSpan>, IComparable<TextSpan>
{
/// <summary>
/// Creates a TextSpan instance beginning with the position Start and having the Length
/// specified with <paramref name="length" />.
/// </summary>
public TextSpan(int start, int length)
{
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start + length < start)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
Start = start;
Length = length;
}
/// <summary>
/// Start point of the span.
/// </summary>
[DataMember(Order = 0)]
public int Start { get; }
/// <summary>
/// End of the span.
/// </summary>
public int End => Start + Length;
/// <summary>
/// Length of the span.
/// </summary>
[DataMember(Order = 1)]
public int Length { get; }
/// <summary>
/// Determines whether or not the span is empty.
/// </summary>
public bool IsEmpty => this.Length == 0;
/// <summary>
/// Determines whether the position lies within the span.
/// </summary>
/// <param name="position">
/// The position to check.
/// </param>
/// <returns>
/// <c>true</c> if the position is greater than or equal to Start and strictly less
/// than End, otherwise <c>false</c>.
/// </returns>
public bool Contains(int position)
{
return unchecked((uint)(position - Start) < (uint)Length);
}
/// <summary>
/// Determines whether <paramref name="span"/> falls completely within this span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the specified span falls completely within this span, otherwise <c>false</c>.
/// </returns>
public bool Contains(TextSpan span)
{
return span.Start >= Start && span.End <= this.End;
}
/// <summary>
/// Determines whether <paramref name="span"/> overlaps this span. Two spans are considered to overlap
/// if they have positions in common and neither is empty. Empty spans do not overlap with any
/// other span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the spans overlap, otherwise <c>false</c>.
/// </returns>
public bool OverlapsWith(TextSpan span)
{
int overlapStart = Math.Max(Start, span.Start);
int overlapEnd = Math.Min(this.End, span.End);
return overlapStart < overlapEnd;
}
/// <summary>
/// Returns the overlap with the given span, or null if there is no overlap.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// The overlap of the spans, or null if the overlap is empty.
/// </returns>
public TextSpan? Overlap(TextSpan span)
{
int overlapStart = Math.Max(Start, span.Start);
int overlapEnd = Math.Min(this.End, span.End);
return overlapStart < overlapEnd
? TextSpan.FromBounds(overlapStart, overlapEnd)
: (TextSpan?)null;
}
/// <summary>
/// Determines whether <paramref name="span"/> intersects this span. Two spans are considered to
/// intersect if they have positions in common or the end of one span
/// coincides with the start of the other span.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// <c>true</c> if the spans intersect, otherwise <c>false</c>.
/// </returns>
public bool IntersectsWith(TextSpan span)
{
return span.Start <= this.End && span.End >= Start;
}
/// <summary>
/// Determines whether <paramref name="position"/> intersects this span.
/// A position is considered to intersect if it is between the start and
/// end positions (inclusive) of this span.
/// </summary>
/// <param name="position">
/// The position to check.
/// </param>
/// <returns>
/// <c>true</c> if the position intersects, otherwise <c>false</c>.
/// </returns>
public bool IntersectsWith(int position)
{
return unchecked((uint)(position - Start) <= (uint)Length);
}
/// <summary>
/// Returns the intersection with the given span, or null if there is no intersection.
/// </summary>
/// <param name="span">
/// The span to check.
/// </param>
/// <returns>
/// The intersection of the spans, or null if the intersection is empty.
/// </returns>
public TextSpan? Intersection(TextSpan span)
{
int intersectStart = Math.Max(Start, span.Start);
int intersectEnd = Math.Min(this.End, span.End);
return intersectStart <= intersectEnd
? TextSpan.FromBounds(intersectStart, intersectEnd)
: (TextSpan?)null;
}
/// <summary>
/// Creates a new <see cref="TextSpan"/> from <paramref name="start" /> and <paramref
/// name="end"/> positions as opposed to a position and length.
///
/// The returned TextSpan contains the range with <paramref name="start"/> inclusive,
/// and <paramref name="end"/> exclusive.
/// </summary>
public static TextSpan FromBounds(int start, int end)
{
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start), CodeAnalysisResources.StartMustNotBeNegative);
}
if (end < start)
{
throw new ArgumentOutOfRangeException(nameof(end), CodeAnalysisResources.EndMustNotBeLessThanStart);
}
return new TextSpan(start, end - start);
}
/// <summary>
/// Determines if two instances of <see cref="TextSpan"/> are the same.
/// </summary>
public static bool operator ==(TextSpan left, TextSpan right)
{
return left.Equals(right);
}
/// <summary>
/// Determines if two instances of <see cref="TextSpan"/> are different.
/// </summary>
public static bool operator !=(TextSpan left, TextSpan right)
{
return !left.Equals(right);
}
/// <summary>
/// Determines if current instance of <see cref="TextSpan"/> is equal to another.
/// </summary>
public bool Equals(TextSpan other)
{
return Start == other.Start && Length == other.Length;
}
/// <summary>
/// Determines if current instance of <see cref="TextSpan"/> is equal to another.
/// </summary>
public override bool Equals(object? obj)
{
return obj is TextSpan && Equals((TextSpan)obj);
}
/// <summary>
/// Produces a hash code for <see cref="TextSpan"/>.
/// </summary>
public override int GetHashCode()
{
return Hash.Combine(Start, Length);
}
/// <summary>
/// Provides a string representation for <see cref="TextSpan"/>.
/// </summary>
public override string ToString()
{
return $"[{Start}..{End})";
}
/// <summary>
/// Compares current instance of <see cref="TextSpan"/> with another.
/// </summary>
public int CompareTo(TextSpan other)
{
var diff = Start - other.Start;
if (diff != 0)
{
return diff;
}
return Length - other.Length;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/ChangeSignature/AbstractChangeSignatureCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.ChangeSignature), Shared]
internal class ChangeSignatureCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public ChangeSignatureCodeRefactoringProvider()
{
}
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
if (span.IsEmpty)
{
var service = document.GetLanguageService<AbstractChangeSignatureService>();
var actions = await service.GetChangeSignatureCodeActionAsync(document, span, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.ChangeSignature), Shared]
internal class ChangeSignatureCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public ChangeSignatureCodeRefactoringProvider()
{
}
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
if (span.IsEmpty)
{
var service = document.GetLanguageService<AbstractChangeSignatureService>();
var actions = await service.GetChangeSignatureCodeActionAsync(document, span, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioAddSolutionItemService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Composition;
using System.IO;
using System.Threading;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export]
[ExportWorkspaceService(typeof(IAddSolutionItemService)), Shared]
internal partial class VisualStudioAddSolutionItemService : IAddSolutionItemService
{
private const string SolutionItemsFolderName = "Solution Items";
private readonly object _gate = new();
private readonly IThreadingContext _threadingContext;
private readonly ConcurrentDictionary<string, FileChangeTracker> _fileChangeTrackers;
private DTE? _dte;
private IVsFileChangeEx? _fileChangeService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioAddSolutionItemService(
IThreadingContext threadingContext)
{
_threadingContext = threadingContext;
_fileChangeTrackers = new ConcurrentDictionary<string, FileChangeTracker>(StringComparer.OrdinalIgnoreCase);
}
public void Initialize(IServiceProvider serviceProvider)
{
_dte = (DTE)serviceProvider.GetService(typeof(DTE));
_fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
}
public void TrackFilePathAndAddSolutionItemWhenFileCreated(string filePath)
{
if (_fileChangeService != null &&
PathUtilities.IsAbsolute(filePath) &&
FileExistsWithGuard(filePath) == false)
{
// Setup a new file change tracker to track file path and
// add newly created file as solution item.
_fileChangeTrackers.GetOrAdd(filePath, CreateTracker);
}
return;
// Local functions
FileChangeTracker CreateTracker(string filePath)
{
var tracker = new FileChangeTracker(_fileChangeService, filePath, _VSFILECHANGEFLAGS.VSFILECHG_Add);
tracker.UpdatedOnDisk += OnFileAdded;
_ = tracker.StartFileChangeListeningAsync();
return tracker;
}
}
private void OnFileAdded(object sender, EventArgs e)
{
var tracker = (FileChangeTracker)sender;
var filePath = tracker.FilePath;
_fileChangeTrackers.TryRemove(filePath, out _);
AddSolutionItemAsync(filePath, CancellationToken.None).Wait();
tracker.UpdatedOnDisk -= OnFileAdded;
tracker.Dispose();
}
public async Task AddSolutionItemAsync(string filePath, CancellationToken cancellationToken)
{
if (_dte == null)
{
return;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
lock (_gate)
{
var solution = (Solution2)_dte.Solution;
if (!TryGetExistingSolutionItemsFolder(solution, filePath, out var solutionItemsFolder, out var hasExistingSolutionItem))
{
solutionItemsFolder = solution.AddSolutionFolder("Solution Items");
}
if (!hasExistingSolutionItem &&
solutionItemsFolder != null &&
FileExistsWithGuard(filePath) == true)
{
solutionItemsFolder.ProjectItems.AddFromFile(filePath);
solution.SaveAs(solution.FileName);
}
}
}
private static bool? FileExistsWithGuard(string filePath)
{
try
{
return File.Exists(filePath);
}
catch (IOException)
{
return null;
}
}
public static bool TryGetExistingSolutionItemsFolder(Solution2 solution, string filePath, out EnvDTE.Project? solutionItemsFolder, out bool hasExistingSolutionItem)
{
solutionItemsFolder = null;
hasExistingSolutionItem = false;
var fileName = PathUtilities.GetFileName(filePath);
foreach (Project project in solution.Projects)
{
if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems &&
project.Name == SolutionItemsFolderName)
{
solutionItemsFolder = project;
foreach (ProjectItem projectItem in solutionItemsFolder.ProjectItems)
{
if (fileName == projectItem.Name)
{
hasExistingSolutionItem = true;
break;
}
}
return true;
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Composition;
using System.IO;
using System.Threading;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export]
[ExportWorkspaceService(typeof(IAddSolutionItemService)), Shared]
internal partial class VisualStudioAddSolutionItemService : IAddSolutionItemService
{
private const string SolutionItemsFolderName = "Solution Items";
private readonly object _gate = new();
private readonly IThreadingContext _threadingContext;
private readonly ConcurrentDictionary<string, FileChangeTracker> _fileChangeTrackers;
private DTE? _dte;
private IVsFileChangeEx? _fileChangeService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioAddSolutionItemService(
IThreadingContext threadingContext)
{
_threadingContext = threadingContext;
_fileChangeTrackers = new ConcurrentDictionary<string, FileChangeTracker>(StringComparer.OrdinalIgnoreCase);
}
public void Initialize(IServiceProvider serviceProvider)
{
_dte = (DTE)serviceProvider.GetService(typeof(DTE));
_fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
}
public void TrackFilePathAndAddSolutionItemWhenFileCreated(string filePath)
{
if (_fileChangeService != null &&
PathUtilities.IsAbsolute(filePath) &&
FileExistsWithGuard(filePath) == false)
{
// Setup a new file change tracker to track file path and
// add newly created file as solution item.
_fileChangeTrackers.GetOrAdd(filePath, CreateTracker);
}
return;
// Local functions
FileChangeTracker CreateTracker(string filePath)
{
var tracker = new FileChangeTracker(_fileChangeService, filePath, _VSFILECHANGEFLAGS.VSFILECHG_Add);
tracker.UpdatedOnDisk += OnFileAdded;
_ = tracker.StartFileChangeListeningAsync();
return tracker;
}
}
private void OnFileAdded(object sender, EventArgs e)
{
var tracker = (FileChangeTracker)sender;
var filePath = tracker.FilePath;
_fileChangeTrackers.TryRemove(filePath, out _);
AddSolutionItemAsync(filePath, CancellationToken.None).Wait();
tracker.UpdatedOnDisk -= OnFileAdded;
tracker.Dispose();
}
public async Task AddSolutionItemAsync(string filePath, CancellationToken cancellationToken)
{
if (_dte == null)
{
return;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
lock (_gate)
{
var solution = (Solution2)_dte.Solution;
if (!TryGetExistingSolutionItemsFolder(solution, filePath, out var solutionItemsFolder, out var hasExistingSolutionItem))
{
solutionItemsFolder = solution.AddSolutionFolder("Solution Items");
}
if (!hasExistingSolutionItem &&
solutionItemsFolder != null &&
FileExistsWithGuard(filePath) == true)
{
solutionItemsFolder.ProjectItems.AddFromFile(filePath);
solution.SaveAs(solution.FileName);
}
}
}
private static bool? FileExistsWithGuard(string filePath)
{
try
{
return File.Exists(filePath);
}
catch (IOException)
{
return null;
}
}
public static bool TryGetExistingSolutionItemsFolder(Solution2 solution, string filePath, out EnvDTE.Project? solutionItemsFolder, out bool hasExistingSolutionItem)
{
solutionItemsFolder = null;
hasExistingSolutionItem = false;
var fileName = PathUtilities.GetFileName(filePath);
foreach (Project project in solution.Projects)
{
if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems &&
project.Name == SolutionItemsFolderName)
{
solutionItemsFolder = project;
foreach (ProjectItem projectItem in solutionItemsFolder.ProjectItems)
{
if (fileName == projectItem.Name)
{
hasExistingSolutionItem = true;
break;
}
}
return true;
}
}
return false;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/Signature.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal class Signature : ISignature
{
private const int MaxParamColumnCount = 100;
private readonly SignatureHelpItem _signatureHelpItem;
public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex)
{
if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length)
{
throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex));
}
this.ApplicableToSpan = applicableToSpan;
_signatureHelpItem = signatureHelpItem;
_parameterIndex = selectedParameterIndex;
}
private bool _isInitialized;
private void EnsureInitialized()
{
if (!_isInitialized)
{
_isInitialized = true;
Initialize();
}
}
private Signature InitializedThis
{
get
{
EnsureInitialized();
return this;
}
}
private IList<TaggedText> _displayParts;
internal IList<TaggedText> DisplayParts => InitializedThis._displayParts;
public ITrackingSpan ApplicableToSpan { get; }
private string _content;
public string Content => InitializedThis._content;
private readonly int _parameterIndex = -1;
public IParameter CurrentParameter
{
get
{
EnsureInitialized();
return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null;
}
}
/// <remarks>
/// The documentation is included in <see cref="Content"/> so that it will be classified.
/// </remarks>
public string Documentation => null;
private ReadOnlyCollection<IParameter> _parameters;
public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters;
private string _prettyPrintedContent;
public string PrettyPrintedContent => InitializedThis._prettyPrintedContent;
// This event is required by the ISignature interface but it's not actually used
// (once created the CurrentParameter property cannot change)
public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged
{
add
{
}
remove
{
}
}
private IList<TaggedText> _prettyPrintedDisplayParts;
internal IList<TaggedText> PrettyPrintedDisplayParts => InitializedThis._prettyPrintedDisplayParts;
private void Initialize()
{
var content = new StringBuilder();
var prettyPrintedContent = new StringBuilder();
var parts = new List<TaggedText>();
var prettyPrintedParts = new List<TaggedText>();
var parameters = new List<IParameter>();
var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts;
var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText();
AddRange(signaturePrefixParts, parts, prettyPrintedParts);
Append(signaturePrefixContent, content, prettyPrintedContent);
var separatorParts = _signatureHelpItem.SeparatorDisplayParts;
var separatorContent = separatorParts.GetFullText();
var newLinePart = new TaggedText(TextTags.LineBreak, "\r\n");
var newLineContent = newLinePart.ToString();
var spacerPart = new TaggedText(TextTags.Space, new string(' ', signaturePrefixContent.Length));
var spacerContent = spacerPart.ToString();
var paramColumnCount = 0;
for (var i = 0; i < _signatureHelpItem.Parameters.Length; i++)
{
var sigHelpParameter = _signatureHelpItem.Parameters[i];
var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts;
var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText();
var parameterParts = AddOptionalBrackets(
sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts);
var parameterContent = parameterParts.GetFullText();
var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts;
var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText();
paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length;
if (i > 0)
{
AddRange(separatorParts, parts, prettyPrintedParts);
Append(separatorContent, content, prettyPrintedContent);
if (paramColumnCount > MaxParamColumnCount)
{
prettyPrintedParts.Add(newLinePart);
prettyPrintedParts.Add(spacerPart);
prettyPrintedContent.Append(newLineContent);
prettyPrintedContent.Append(spacerContent);
paramColumnCount = 0;
}
}
AddRange(parameterPrefixParts, parts, prettyPrintedParts);
Append(parameterPrefixContext, content, prettyPrintedContent);
parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length));
AddRange(parameterParts, parts, prettyPrintedParts);
Append(parameterContent, content, prettyPrintedContent);
AddRange(parameterSuffixParts, parts, prettyPrintedParts);
Append(parameterSuffixContext, content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent);
if (_parameterIndex >= 0)
{
var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex];
AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts);
Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent);
var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList();
if (documentation.Count > 0)
{
AddRange(new[] { newLinePart }, parts, prettyPrintedParts);
Append(newLineContent, content, prettyPrintedContent);
AddRange(documentation, parts, prettyPrintedParts);
Append(documentation.GetFullText(), content, prettyPrintedContent);
}
_content = content.ToString();
_prettyPrintedContent = prettyPrintedContent.ToString();
_displayParts = parts.ToImmutableArrayOrEmpty();
_prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty();
_parameters = parameters.ToReadOnlyCollection();
}
private static void AddRange(IList<TaggedText> values, List<TaggedText> parts, List<TaggedText> prettyPrintedParts)
{
parts.AddRange(values);
prettyPrintedParts.AddRange(values);
}
private static void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent)
{
content.Append(text);
prettyPrintedContent.Append(text);
}
private static IList<TaggedText> AddOptionalBrackets(bool isOptional, IList<TaggedText> list)
{
if (isOptional)
{
var result = new List<TaggedText>();
result.Add(new TaggedText(TextTags.Punctuation, "["));
result.AddRange(list);
result.Add(new TaggedText(TextTags.Punctuation, "]"));
return result;
}
return list;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal class Signature : ISignature
{
private const int MaxParamColumnCount = 100;
private readonly SignatureHelpItem _signatureHelpItem;
public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex)
{
if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length)
{
throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex));
}
this.ApplicableToSpan = applicableToSpan;
_signatureHelpItem = signatureHelpItem;
_parameterIndex = selectedParameterIndex;
}
private bool _isInitialized;
private void EnsureInitialized()
{
if (!_isInitialized)
{
_isInitialized = true;
Initialize();
}
}
private Signature InitializedThis
{
get
{
EnsureInitialized();
return this;
}
}
private IList<TaggedText> _displayParts;
internal IList<TaggedText> DisplayParts => InitializedThis._displayParts;
public ITrackingSpan ApplicableToSpan { get; }
private string _content;
public string Content => InitializedThis._content;
private readonly int _parameterIndex = -1;
public IParameter CurrentParameter
{
get
{
EnsureInitialized();
return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null;
}
}
/// <remarks>
/// The documentation is included in <see cref="Content"/> so that it will be classified.
/// </remarks>
public string Documentation => null;
private ReadOnlyCollection<IParameter> _parameters;
public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters;
private string _prettyPrintedContent;
public string PrettyPrintedContent => InitializedThis._prettyPrintedContent;
// This event is required by the ISignature interface but it's not actually used
// (once created the CurrentParameter property cannot change)
public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged
{
add
{
}
remove
{
}
}
private IList<TaggedText> _prettyPrintedDisplayParts;
internal IList<TaggedText> PrettyPrintedDisplayParts => InitializedThis._prettyPrintedDisplayParts;
private void Initialize()
{
var content = new StringBuilder();
var prettyPrintedContent = new StringBuilder();
var parts = new List<TaggedText>();
var prettyPrintedParts = new List<TaggedText>();
var parameters = new List<IParameter>();
var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts;
var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText();
AddRange(signaturePrefixParts, parts, prettyPrintedParts);
Append(signaturePrefixContent, content, prettyPrintedContent);
var separatorParts = _signatureHelpItem.SeparatorDisplayParts;
var separatorContent = separatorParts.GetFullText();
var newLinePart = new TaggedText(TextTags.LineBreak, "\r\n");
var newLineContent = newLinePart.ToString();
var spacerPart = new TaggedText(TextTags.Space, new string(' ', signaturePrefixContent.Length));
var spacerContent = spacerPart.ToString();
var paramColumnCount = 0;
for (var i = 0; i < _signatureHelpItem.Parameters.Length; i++)
{
var sigHelpParameter = _signatureHelpItem.Parameters[i];
var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts;
var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText();
var parameterParts = AddOptionalBrackets(
sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts);
var parameterContent = parameterParts.GetFullText();
var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts;
var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText();
paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length;
if (i > 0)
{
AddRange(separatorParts, parts, prettyPrintedParts);
Append(separatorContent, content, prettyPrintedContent);
if (paramColumnCount > MaxParamColumnCount)
{
prettyPrintedParts.Add(newLinePart);
prettyPrintedParts.Add(spacerPart);
prettyPrintedContent.Append(newLineContent);
prettyPrintedContent.Append(spacerContent);
paramColumnCount = 0;
}
}
AddRange(parameterPrefixParts, parts, prettyPrintedParts);
Append(parameterPrefixContext, content, prettyPrintedContent);
parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length));
AddRange(parameterParts, parts, prettyPrintedParts);
Append(parameterContent, content, prettyPrintedContent);
AddRange(parameterSuffixParts, parts, prettyPrintedParts);
Append(parameterSuffixContext, content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent);
if (_parameterIndex >= 0)
{
var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex];
AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts);
Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent);
var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList();
if (documentation.Count > 0)
{
AddRange(new[] { newLinePart }, parts, prettyPrintedParts);
Append(newLineContent, content, prettyPrintedContent);
AddRange(documentation, parts, prettyPrintedParts);
Append(documentation.GetFullText(), content, prettyPrintedContent);
}
_content = content.ToString();
_prettyPrintedContent = prettyPrintedContent.ToString();
_displayParts = parts.ToImmutableArrayOrEmpty();
_prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty();
_parameters = parameters.ToReadOnlyCollection();
}
private static void AddRange(IList<TaggedText> values, List<TaggedText> parts, List<TaggedText> prettyPrintedParts)
{
parts.AddRange(values);
prettyPrintedParts.AddRange(values);
}
private static void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent)
{
content.Append(text);
prettyPrintedContent.Append(text);
}
private static IList<TaggedText> AddOptionalBrackets(bool isOptional, IList<TaggedText> list)
{
if (isOptional)
{
var result = new List<TaggedText>();
result.Add(new TaggedText(TextTags.Punctuation, "["));
result.AddRange(list);
result.Add(new TaggedText(TextTags.Punctuation, "]"));
return result;
}
return list;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DefaultPersistentStorageServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// A service that enables storing and retrieving of information associated with solutions,
/// projects or documents across runtime sessions.
/// </summary>
[ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), ServiceLayer.Default), Shared]
internal class DefaultPersistentStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultPersistentStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> NoOpPersistentStorageService.GetOrThrow(workspaceServices.Workspace.Options);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// A service that enables storing and retrieving of information associated with solutions,
/// projects or documents across runtime sessions.
/// </summary>
[ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), ServiceLayer.Default), Shared]
internal class DefaultPersistentStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultPersistentStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> NoOpPersistentStorageService.GetOrThrow(workspaceServices.Workspace.Options);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/CSharp/Portable/Symbols/SymbolEqualityComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SymbolEqualityComparer : EqualityComparer<Symbol>
{
internal static readonly EqualityComparer<Symbol> ConsiderEverything = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything);
internal static readonly EqualityComparer<Symbol> IgnoringTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static EqualityComparer<Symbol> IncludeNullability => ConsiderEverything;
/// <summary>
/// A comparer that treats dynamic and object as "the same" types, and also ignores tuple element names differences.
/// </summary>
internal static readonly EqualityComparer<Symbol> IgnoringDynamicTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static readonly EqualityComparer<Symbol> IgnoringNullable = new SymbolEqualityComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static readonly EqualityComparer<Symbol> ObliviousNullableModifierMatchesAny = new SymbolEqualityComparer(TypeCompareKind.ObliviousNullableModifierMatchesAny);
internal static readonly EqualityComparer<Symbol> AllIgnoreOptions = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions);
internal static readonly EqualityComparer<Symbol> AllIgnoreOptionsPlusNullableWithUnknownMatchesAny =
new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
internal static readonly EqualityComparer<Symbol> CLRSignature = new SymbolEqualityComparer(TypeCompareKind.CLRSignatureCompareOptions);
private readonly TypeCompareKind _comparison;
private SymbolEqualityComparer(TypeCompareKind comparison)
{
_comparison = comparison;
}
public override int GetHashCode(Symbol obj)
{
return obj is null ? 0 : obj.GetHashCode();
}
public override bool Equals(Symbol x, Symbol y)
{
return x is null ? y is null : x.Equals(y, _comparison);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SymbolEqualityComparer : EqualityComparer<Symbol>
{
internal static readonly EqualityComparer<Symbol> ConsiderEverything = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything);
internal static readonly EqualityComparer<Symbol> IgnoringTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static EqualityComparer<Symbol> IncludeNullability => ConsiderEverything;
/// <summary>
/// A comparer that treats dynamic and object as "the same" types, and also ignores tuple element names differences.
/// </summary>
internal static readonly EqualityComparer<Symbol> IgnoringDynamicTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static readonly EqualityComparer<Symbol> IgnoringNullable = new SymbolEqualityComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes);
internal static readonly EqualityComparer<Symbol> ObliviousNullableModifierMatchesAny = new SymbolEqualityComparer(TypeCompareKind.ObliviousNullableModifierMatchesAny);
internal static readonly EqualityComparer<Symbol> AllIgnoreOptions = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions);
internal static readonly EqualityComparer<Symbol> AllIgnoreOptionsPlusNullableWithUnknownMatchesAny =
new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
internal static readonly EqualityComparer<Symbol> CLRSignature = new SymbolEqualityComparer(TypeCompareKind.CLRSignatureCompareOptions);
private readonly TypeCompareKind _comparison;
private SymbolEqualityComparer(TypeCompareKind comparison)
{
_comparison = comparison;
}
public override int GetHashCode(Symbol obj)
{
return obj is null ? 0 : obj.GetHashCode();
}
public override bool Equals(Symbol x, Symbol y)
{
return x is null ? y is null : x.Equals(y, _comparison);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseImplicitObjectCreation), Shared]
internal class CSharpUseImplicitObjectCreationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpUseImplicitObjectCreationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.IsSuppressed;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// process from inside->out so that outer rewrites see the effects of inner changes.
foreach (var diagnostic in diagnostics.OrderBy(d => d.Location.SourceSpan.End))
FixOne(editor, diagnostic, cancellationToken);
return Task.CompletedTask;
}
private static void FixOne(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(node, (current, _) =>
{
var currentObjectCreation = (ObjectCreationExpressionSyntax)current;
return SyntaxFactory.ImplicitObjectCreationExpression(
WithoutTrailingWhitespace(currentObjectCreation.NewKeyword),
currentObjectCreation.ArgumentList ?? SyntaxFactory.ArgumentList(),
currentObjectCreation.Initializer);
});
}
private static SyntaxToken WithoutTrailingWhitespace(SyntaxToken newKeyword)
{
return newKeyword.TrailingTrivia.All(t => t.IsWhitespace())
? newKeyword.WithoutTrailingTrivia()
: newKeyword;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_new, createChangedDocument, CSharpAnalyzersResources.Use_new)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseImplicitObjectCreation), Shared]
internal class CSharpUseImplicitObjectCreationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpUseImplicitObjectCreationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.IsSuppressed;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// process from inside->out so that outer rewrites see the effects of inner changes.
foreach (var diagnostic in diagnostics.OrderBy(d => d.Location.SourceSpan.End))
FixOne(editor, diagnostic, cancellationToken);
return Task.CompletedTask;
}
private static void FixOne(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(node, (current, _) =>
{
var currentObjectCreation = (ObjectCreationExpressionSyntax)current;
return SyntaxFactory.ImplicitObjectCreationExpression(
WithoutTrailingWhitespace(currentObjectCreation.NewKeyword),
currentObjectCreation.ArgumentList ?? SyntaxFactory.ArgumentList(),
currentObjectCreation.Initializer);
});
}
private static SyntaxToken WithoutTrailingWhitespace(SyntaxToken newKeyword)
{
return newKeyword.TrailingTrivia.All(t => t.IsWhitespace())
? newKeyword.WithoutTrailingTrivia()
: newKeyword;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_new, createChangedDocument, CSharpAnalyzersResources.Use_new)
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Obsolete. Use <see cref="FindSymbolAtPositionAsync(SemanticModel, int, Workspace, CancellationToken)"/>.
/// </summary>
[Obsolete("Use FindSymbolAtPositionAsync instead.")]
public static ISymbol FindSymbolAtPosition(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken = default)
{
return FindSymbolAtPositionAsync(semanticModel, position, workspace, cancellationToken).WaitAndGetResult(cancellationToken);
}
/// <summary>
/// Finds the symbol that is associated with a position in the text of a document.
/// </summary>
/// <param name="semanticModel">The semantic model associated with the document.</param>
/// <param name="position">The character position within the document.</param>
/// <param name="workspace">A workspace to provide context.</param>
/// <param name="cancellationToken">A CancellationToken.</param>
public static async Task<ISymbol> FindSymbolAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken = default)
{
if (semanticModel is null)
throw new ArgumentNullException(nameof(semanticModel));
if (workspace is null)
throw new ArgumentNullException(nameof(workspace));
var semanticInfo = await GetSemanticInfoAtPositionAsync(
semanticModel, position, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
return semanticInfo.GetAnySymbol(includeType: false);
}
internal static async Task<TokenSemanticInfo> GetSemanticInfoAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken)
{
var token = await GetTokenAtPositionAsync(semanticModel, position, workspace, cancellationToken).ConfigureAwait(false);
if (token != default &&
token.Span.IntersectsWith(position))
{
return semanticModel.GetSemanticInfo(token, workspace, cancellationToken);
}
return TokenSemanticInfo.Empty;
}
private static Task<SyntaxToken> GetTokenAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
var syntaxFacts = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>();
return syntaxTree.GetTouchingTokenAsync(position, syntaxFacts.IsBindableToken, cancellationToken, findInsideTrivia: true);
}
public static async Task<ISymbol> FindSymbolAtPositionAsync(
Document document,
int position,
CancellationToken cancellationToken = default)
{
if (document is null)
throw new ArgumentNullException(nameof(document));
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await FindSymbolAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds the definition symbol declared in source code for a corresponding reference symbol.
/// Returns null if no such symbol can be found in the specified solution.
/// </summary>
public static Task<ISymbol?> FindSourceDefinitionAsync(
ISymbol? symbol, Solution solution, CancellationToken cancellationToken = default)
{
if (symbol != null)
{
symbol = symbol.GetOriginalUnreducedDefinition();
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Local:
case SymbolKind.NamedType:
case SymbolKind.Parameter:
case SymbolKind.Property:
case SymbolKind.TypeParameter:
case SymbolKind.Namespace:
return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken);
}
}
return SpecializedTasks.Null<ISymbol>();
}
private static async Task<ISymbol?> FindSourceDefinitionWorkerAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
// If it's already in source, then we might already be done
if (InSource(symbol))
{
// If our symbol doesn't have a containing assembly, there's nothing better we can do to map this
// symbol somewhere else. The common case for this is a merged INamespaceSymbol that spans assemblies.
if (symbol.ContainingAssembly == null)
{
return symbol;
}
// Just because it's a source symbol doesn't mean we have the final symbol we actually want. In retargeting cases,
// the retargeted symbol is from "source" but isn't equal to the actual source definition in the other project. Thus,
// we only want to return symbols from source here if it actually came from a project's compilation's assembly. If it isn't
// then we have a retargeting scenario and want to take our usual path below as if it was a metadata reference
foreach (var sourceProject in solution.Projects)
{
// If our symbol is actually a "regular" source symbol, then we know the compilation is holding the symbol alive
// and thus TryGetCompilation is sufficient. For another example of this pattern, see Solution.GetProject(IAssemblySymbol)
// which we happen to call below.
if (sourceProject.TryGetCompilation(out var compilation))
{
if (symbol.ContainingAssembly.Equals(compilation.Assembly))
{
return symbol;
}
}
}
}
else if (!symbol.Locations.Any(loc => loc.IsInMetadata))
{
// We have a symbol that's neither in source nor metadata
return null;
}
var project = solution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null && project.SupportsCompilation)
{
var symbolId = symbol.GetSymbolKey(cancellationToken);
var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
var result = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken);
if (result.Symbol != null && InSource(result.Symbol))
{
return result.Symbol;
}
else
{
return result.CandidateSymbols.FirstOrDefault(InSource);
}
}
return null;
}
private static bool InSource(ISymbol symbol)
{
return symbol.Locations.Any(loc => loc.IsInSource);
}
/// <summary>
/// Finds symbols in the given compilation that are similar to the specified symbol.
///
/// A found symbol may be the exact same symbol instance if the compilation is the origin of the specified symbol,
/// or it may be a different symbol instance if the compilation is not the originating compilation.
///
/// Multiple symbols may be returned if there are ambiguous matches.
/// No symbols may be returned if the compilation does not define or have access to a similar symbol.
/// </summary>
/// <param name="symbol">The symbol to find corresponding matches for.</param>
/// <param name="compilation">A compilation to find the corresponding symbol within. The compilation may or may not be the origin of the symbol.</param>
/// <param name="cancellationToken">A CancellationToken.</param>
/// <returns></returns>
public static IEnumerable<TSymbol> FindSimilarSymbols<TSymbol>(TSymbol symbol, Compilation compilation, CancellationToken cancellationToken = default)
where TSymbol : ISymbol
{
if (symbol is null)
throw new ArgumentNullException(nameof(symbol));
if (compilation is null)
throw new ArgumentNullException(nameof(compilation));
var key = symbol.GetSymbolKey(cancellationToken);
// We may be talking about different compilations. So do not try to resolve locations.
var result = new HashSet<TSymbol>();
var resolution = key.Resolve(compilation, cancellationToken: cancellationToken);
foreach (var current in resolution.OfType<TSymbol>())
{
result.Add(current);
}
return result;
}
/// <summary>
/// If <paramref name="symbol"/> is declared in a linked file, then this function returns all the symbols that
/// are defined by the same symbol's syntax in the all projects that the linked file is referenced from.
/// <para/>
/// In order to be returned the other symbols must have the same <see cref="ISymbol.Name"/> and <see
/// cref="ISymbol.Kind"/> as <paramref name="symbol"/>. This matches general user intuition that these are all
/// the 'same' symbol, and should be examined, regardless of the project context and <see cref="ISymbol"/> they
/// originally started with.
/// </summary>
internal static async Task<ImmutableArray<ISymbol>> FindLinkedSymbolsAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
// Add the original symbol to the result set.
var linkedSymbols = new HashSet<ISymbol> { symbol };
foreach (var location in symbol.DeclaringSyntaxReferences)
{
var originalDocument = solution.GetDocument(location.SyntaxTree);
// GetDocument will return null for locations in #load'ed trees. TODO: Remove this check and add logic
// to fetch the #load'ed tree's Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (originalDocument == null)
{
Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles);
continue;
}
foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var linkedSyntaxRoot = await linkedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var linkedNode = linkedSyntaxRoot.FindNode(location.Span, getInnermostNodeForTie: true);
var semanticModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken);
if (linkedSymbol != null &&
linkedSymbol.Kind == symbol.Kind &&
linkedSymbol.Name == symbol.Name)
{
linkedSymbols.Add(linkedSymbol);
}
}
}
return linkedSymbols.ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Obsolete. Use <see cref="FindSymbolAtPositionAsync(SemanticModel, int, Workspace, CancellationToken)"/>.
/// </summary>
[Obsolete("Use FindSymbolAtPositionAsync instead.")]
public static ISymbol FindSymbolAtPosition(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken = default)
{
return FindSymbolAtPositionAsync(semanticModel, position, workspace, cancellationToken).WaitAndGetResult(cancellationToken);
}
/// <summary>
/// Finds the symbol that is associated with a position in the text of a document.
/// </summary>
/// <param name="semanticModel">The semantic model associated with the document.</param>
/// <param name="position">The character position within the document.</param>
/// <param name="workspace">A workspace to provide context.</param>
/// <param name="cancellationToken">A CancellationToken.</param>
public static async Task<ISymbol> FindSymbolAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken = default)
{
if (semanticModel is null)
throw new ArgumentNullException(nameof(semanticModel));
if (workspace is null)
throw new ArgumentNullException(nameof(workspace));
var semanticInfo = await GetSemanticInfoAtPositionAsync(
semanticModel, position, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
return semanticInfo.GetAnySymbol(includeType: false);
}
internal static async Task<TokenSemanticInfo> GetSemanticInfoAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken)
{
var token = await GetTokenAtPositionAsync(semanticModel, position, workspace, cancellationToken).ConfigureAwait(false);
if (token != default &&
token.Span.IntersectsWith(position))
{
return semanticModel.GetSemanticInfo(token, workspace, cancellationToken);
}
return TokenSemanticInfo.Empty;
}
private static Task<SyntaxToken> GetTokenAtPositionAsync(
SemanticModel semanticModel,
int position,
Workspace workspace,
CancellationToken cancellationToken)
{
var syntaxTree = semanticModel.SyntaxTree;
var syntaxFacts = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>();
return syntaxTree.GetTouchingTokenAsync(position, syntaxFacts.IsBindableToken, cancellationToken, findInsideTrivia: true);
}
public static async Task<ISymbol> FindSymbolAtPositionAsync(
Document document,
int position,
CancellationToken cancellationToken = default)
{
if (document is null)
throw new ArgumentNullException(nameof(document));
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await FindSymbolAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds the definition symbol declared in source code for a corresponding reference symbol.
/// Returns null if no such symbol can be found in the specified solution.
/// </summary>
public static Task<ISymbol?> FindSourceDefinitionAsync(
ISymbol? symbol, Solution solution, CancellationToken cancellationToken = default)
{
if (symbol != null)
{
symbol = symbol.GetOriginalUnreducedDefinition();
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Local:
case SymbolKind.NamedType:
case SymbolKind.Parameter:
case SymbolKind.Property:
case SymbolKind.TypeParameter:
case SymbolKind.Namespace:
return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken);
}
}
return SpecializedTasks.Null<ISymbol>();
}
private static async Task<ISymbol?> FindSourceDefinitionWorkerAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
// If it's already in source, then we might already be done
if (InSource(symbol))
{
// If our symbol doesn't have a containing assembly, there's nothing better we can do to map this
// symbol somewhere else. The common case for this is a merged INamespaceSymbol that spans assemblies.
if (symbol.ContainingAssembly == null)
{
return symbol;
}
// Just because it's a source symbol doesn't mean we have the final symbol we actually want. In retargeting cases,
// the retargeted symbol is from "source" but isn't equal to the actual source definition in the other project. Thus,
// we only want to return symbols from source here if it actually came from a project's compilation's assembly. If it isn't
// then we have a retargeting scenario and want to take our usual path below as if it was a metadata reference
foreach (var sourceProject in solution.Projects)
{
// If our symbol is actually a "regular" source symbol, then we know the compilation is holding the symbol alive
// and thus TryGetCompilation is sufficient. For another example of this pattern, see Solution.GetProject(IAssemblySymbol)
// which we happen to call below.
if (sourceProject.TryGetCompilation(out var compilation))
{
if (symbol.ContainingAssembly.Equals(compilation.Assembly))
{
return symbol;
}
}
}
}
else if (!symbol.Locations.Any(loc => loc.IsInMetadata))
{
// We have a symbol that's neither in source nor metadata
return null;
}
var project = solution.GetProject(symbol.ContainingAssembly, cancellationToken);
if (project != null && project.SupportsCompilation)
{
var symbolId = symbol.GetSymbolKey(cancellationToken);
var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
var result = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken);
if (result.Symbol != null && InSource(result.Symbol))
{
return result.Symbol;
}
else
{
return result.CandidateSymbols.FirstOrDefault(InSource);
}
}
return null;
}
private static bool InSource(ISymbol symbol)
{
return symbol.Locations.Any(loc => loc.IsInSource);
}
/// <summary>
/// Finds symbols in the given compilation that are similar to the specified symbol.
///
/// A found symbol may be the exact same symbol instance if the compilation is the origin of the specified symbol,
/// or it may be a different symbol instance if the compilation is not the originating compilation.
///
/// Multiple symbols may be returned if there are ambiguous matches.
/// No symbols may be returned if the compilation does not define or have access to a similar symbol.
/// </summary>
/// <param name="symbol">The symbol to find corresponding matches for.</param>
/// <param name="compilation">A compilation to find the corresponding symbol within. The compilation may or may not be the origin of the symbol.</param>
/// <param name="cancellationToken">A CancellationToken.</param>
/// <returns></returns>
public static IEnumerable<TSymbol> FindSimilarSymbols<TSymbol>(TSymbol symbol, Compilation compilation, CancellationToken cancellationToken = default)
where TSymbol : ISymbol
{
if (symbol is null)
throw new ArgumentNullException(nameof(symbol));
if (compilation is null)
throw new ArgumentNullException(nameof(compilation));
var key = symbol.GetSymbolKey(cancellationToken);
// We may be talking about different compilations. So do not try to resolve locations.
var result = new HashSet<TSymbol>();
var resolution = key.Resolve(compilation, cancellationToken: cancellationToken);
foreach (var current in resolution.OfType<TSymbol>())
{
result.Add(current);
}
return result;
}
/// <summary>
/// If <paramref name="symbol"/> is declared in a linked file, then this function returns all the symbols that
/// are defined by the same symbol's syntax in the all projects that the linked file is referenced from.
/// <para/>
/// In order to be returned the other symbols must have the same <see cref="ISymbol.Name"/> and <see
/// cref="ISymbol.Kind"/> as <paramref name="symbol"/>. This matches general user intuition that these are all
/// the 'same' symbol, and should be examined, regardless of the project context and <see cref="ISymbol"/> they
/// originally started with.
/// </summary>
internal static async Task<ImmutableArray<ISymbol>> FindLinkedSymbolsAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
// Add the original symbol to the result set.
var linkedSymbols = new HashSet<ISymbol> { symbol };
foreach (var location in symbol.DeclaringSyntaxReferences)
{
var originalDocument = solution.GetDocument(location.SyntaxTree);
// GetDocument will return null for locations in #load'ed trees. TODO: Remove this check and add logic
// to fetch the #load'ed tree's Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (originalDocument == null)
{
Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles);
continue;
}
foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var linkedSyntaxRoot = await linkedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var linkedNode = linkedSyntaxRoot.FindNode(location.Span, getInnermostNodeForTie: true);
var semanticModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken);
if (linkedSymbol != null &&
linkedSymbol.Kind == symbol.Kind &&
linkedSymbol.Name == symbol.Name)
{
linkedSymbols.Add(linkedSymbol);
}
}
}
return linkedSymbols.ToImmutableArray();
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using Xunit;
#pragma warning disable IDE0039 // Use local function
namespace Microsoft.CodeAnalysis.UnitTests
{
[SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")]
public class SpecializedTasksTests
{
private record StateType;
private record IntermediateType;
private record ResultType;
[Fact]
public void WhenAll_Null()
{
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void WhenAll_Empty()
{
var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>());
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Same(Array.Empty<int>(), whenAll.Result);
}
[Fact]
public void WhenAll_AllCompletedSuccessfully()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) });
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Equal(new[] { 0, 1 }, whenAll.Result);
}
[Fact]
public void WhenAll_CompletedButCanceled()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) });
Assert.True(whenAll.IsCompleted);
Assert.False(whenAll.IsCompletedSuccessfully);
Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll);
}
[Fact]
public void WhenAll_NotYetCompleted()
{
var completionSource = new TaskCompletionSource<int>();
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) });
Assert.False(whenAll.IsCompleted);
completionSource.SetResult(0);
Assert.True(whenAll.IsCompleted);
Debug.Assert(whenAll.IsCompleted);
Assert.Equal(new[] { 0 }, whenAll.Result);
}
[Fact]
public void Transform_ArgumentValidation()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken));
Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void Transform_SyncCompletedFunction_CompletedTransform()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCompletedSuccessfully);
Assert.NotNull(task.Result);
}
[Fact]
public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CompletedTransform()
{
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
Assert.NotNull(await task);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
cts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsFaulted);
var exception = Assert.Throws<InvalidOperationException>(() => task.Result);
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask());
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using Xunit;
#pragma warning disable IDE0039 // Use local function
namespace Microsoft.CodeAnalysis.UnitTests
{
[SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")]
public class SpecializedTasksTests
{
private record StateType;
private record IntermediateType;
private record ResultType;
[Fact]
public void WhenAll_Null()
{
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void WhenAll_Empty()
{
var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>());
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Same(Array.Empty<int>(), whenAll.Result);
}
[Fact]
public void WhenAll_AllCompletedSuccessfully()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) });
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Equal(new[] { 0, 1 }, whenAll.Result);
}
[Fact]
public void WhenAll_CompletedButCanceled()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) });
Assert.True(whenAll.IsCompleted);
Assert.False(whenAll.IsCompletedSuccessfully);
Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll);
}
[Fact]
public void WhenAll_NotYetCompleted()
{
var completionSource = new TaskCompletionSource<int>();
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) });
Assert.False(whenAll.IsCompleted);
completionSource.SetResult(0);
Assert.True(whenAll.IsCompleted);
Debug.Assert(whenAll.IsCompleted);
Assert.Equal(new[] { 0 }, whenAll.Result);
}
[Fact]
public void Transform_ArgumentValidation()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken));
Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void Transform_SyncCompletedFunction_CompletedTransform()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCompletedSuccessfully);
Assert.NotNull(task.Result);
}
[Fact]
public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CompletedTransform()
{
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
Assert.NotNull(await task);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
cts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsFaulted);
var exception = Assert.Throws<InvalidOperationException>(() => task.Result);
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask());
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypescriptNavigationBarItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal class VSTypescriptNavigationBarItem
{
public string Text { get; }
public VSTypeScriptGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<VSTypescriptNavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; }
public VSTypescriptNavigationBarItem(
string text,
VSTypeScriptGlyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<VSTypescriptNavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans.NullToEmpty();
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal class VSTypescriptNavigationBarItem
{
public string Text { get; }
public VSTypeScriptGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<VSTypescriptNavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; }
public VSTypescriptNavigationBarItem(
string text,
VSTypeScriptGlyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<VSTypescriptNavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans.NullToEmpty();
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpNavigationBar.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpNavigationBar : AbstractEditorTest
{
private const string TestSource = @"
class C
{
public void M(int i) { }
private C $$this[int index] { get { return null; } set { } }
public static bool operator ==(C c1, C c2) { return true; }
public static bool operator !=(C c1, C c2) { return false; }
}
struct S
{
int Goo() { }
void Bar() { }
}";
protected override string LanguageName => LanguageNames.CSharp;
public CSharpNavigationBar(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpNavigationBar))
{
}
public override async Task DisposeAsync()
{
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "True");
await base.DisposeAsync();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar()
{
SetUpEditor(TestSource);
VisualStudio.Editor.PlaceCaret("this", charsOffset: 1);
VisualStudio.Editor.ExpandMemberNavBar();
var expectedItems = new[]
{
"M(int i)",
"operator !=(C c1, C c2)",
"operator ==(C c1, C c2)",
"this[int index]"
};
Assert.Equal(expectedItems, VisualStudio.Editor.GetMemberNavBarItems());
VisualStudio.Editor.SelectMemberNavBarItem("operator !=(C c1, C c2)");
VisualStudio.Editor.Verify.CurrentLineText("public static bool operator $$!=(C c1, C c2) { return false; }", assertCaretPosition: true, trimWhitespace: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar2()
{
SetUpEditor(TestSource);
VerifyLeftSelected("C");
VerifyRightSelected("this[int index]");
VisualStudio.Editor.ExpandTypeNavBar();
VisualStudio.Editor.SelectTypeNavBarItem("S");
VerifyLeftSelected("S");
VerifyRightSelected("Goo()");
VisualStudio.Editor.Verify.CurrentLineText("struct $$S", assertCaretPosition: true, trimWhitespace: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar3()
{
SetUpEditor(@"
struct S$$
{
int Goo() { }
void Bar() { }
}");
VisualStudio.Editor.ExpandMemberNavBar();
var expectedItems = new[]
{
"Bar()",
"Goo()",
};
Assert.Equal(expectedItems, VisualStudio.Editor.GetMemberNavBarItems());
VisualStudio.Editor.SelectMemberNavBarItem("Bar()");
VisualStudio.Editor.Verify.CurrentLineText("void $$Bar() { }", assertCaretPosition: true, trimWhitespace: true);
VisualStudio.ExecuteCommand("Edit.LineUp");
VerifyRightSelected("Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void TestSplitWindow()
{
VisualStudio.Editor.SetText(@"
class C
{
public void M(int i) { }
private C this[int index] { get { return null; } set { } }
}
struct S
{
int Goo() { }
void Bar() { }
}");
VisualStudio.ExecuteCommand("Window.Split");
VisualStudio.Editor.PlaceCaret("this", charsOffset: 1);
VerifyLeftSelected("C");
VerifyRightSelected("this[int index]");
VisualStudio.ExecuteCommand("Window.NextSplitPane");
VisualStudio.Editor.PlaceCaret("Goo", charsOffset: 1);
VerifyLeftSelected("S");
VerifyRightSelected("Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyOption()
{
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "False");
Assert.False(VisualStudio.Editor.IsNavBarEnabled());
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "True");
Assert.True(VisualStudio.Editor.IsNavBarEnabled());
}
private void VerifyLeftSelected(string expected)
{
Assert.Equal(expected, VisualStudio.Editor.GetTypeNavBarSelection());
}
private void VerifyRightSelected(string expected)
{
Assert.Equal(expected, VisualStudio.Editor.GetMemberNavBarSelection());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpNavigationBar : AbstractEditorTest
{
private const string TestSource = @"
class C
{
public void M(int i) { }
private C $$this[int index] { get { return null; } set { } }
public static bool operator ==(C c1, C c2) { return true; }
public static bool operator !=(C c1, C c2) { return false; }
}
struct S
{
int Goo() { }
void Bar() { }
}";
protected override string LanguageName => LanguageNames.CSharp;
public CSharpNavigationBar(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpNavigationBar))
{
}
public override async Task DisposeAsync()
{
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "True");
await base.DisposeAsync();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar()
{
SetUpEditor(TestSource);
VisualStudio.Editor.PlaceCaret("this", charsOffset: 1);
VisualStudio.Editor.ExpandMemberNavBar();
var expectedItems = new[]
{
"M(int i)",
"operator !=(C c1, C c2)",
"operator ==(C c1, C c2)",
"this[int index]"
};
Assert.Equal(expectedItems, VisualStudio.Editor.GetMemberNavBarItems());
VisualStudio.Editor.SelectMemberNavBarItem("operator !=(C c1, C c2)");
VisualStudio.Editor.Verify.CurrentLineText("public static bool operator $$!=(C c1, C c2) { return false; }", assertCaretPosition: true, trimWhitespace: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar2()
{
SetUpEditor(TestSource);
VerifyLeftSelected("C");
VerifyRightSelected("this[int index]");
VisualStudio.Editor.ExpandTypeNavBar();
VisualStudio.Editor.SelectTypeNavBarItem("S");
VerifyLeftSelected("S");
VerifyRightSelected("Goo()");
VisualStudio.Editor.Verify.CurrentLineText("struct $$S", assertCaretPosition: true, trimWhitespace: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyNavBar3()
{
SetUpEditor(@"
struct S$$
{
int Goo() { }
void Bar() { }
}");
VisualStudio.Editor.ExpandMemberNavBar();
var expectedItems = new[]
{
"Bar()",
"Goo()",
};
Assert.Equal(expectedItems, VisualStudio.Editor.GetMemberNavBarItems());
VisualStudio.Editor.SelectMemberNavBarItem("Bar()");
VisualStudio.Editor.Verify.CurrentLineText("void $$Bar() { }", assertCaretPosition: true, trimWhitespace: true);
VisualStudio.ExecuteCommand("Edit.LineUp");
VerifyRightSelected("Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void TestSplitWindow()
{
VisualStudio.Editor.SetText(@"
class C
{
public void M(int i) { }
private C this[int index] { get { return null; } set { } }
}
struct S
{
int Goo() { }
void Bar() { }
}");
VisualStudio.ExecuteCommand("Window.Split");
VisualStudio.Editor.PlaceCaret("this", charsOffset: 1);
VerifyLeftSelected("C");
VerifyRightSelected("this[int index]");
VisualStudio.ExecuteCommand("Window.NextSplitPane");
VisualStudio.Editor.PlaceCaret("Goo", charsOffset: 1);
VerifyLeftSelected("S");
VerifyRightSelected("Goo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)]
public void VerifyOption()
{
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "False");
Assert.False(VisualStudio.Editor.IsNavBarEnabled());
VisualStudio.Workspace.SetFeatureOption("NavigationBarOptions", "ShowNavigationBar", "C#", "True");
Assert.True(VisualStudio.Editor.IsNavBarEnabled());
}
private void VerifyLeftSelected(string expected)
{
Assert.Equal(expected, VisualStudio.Editor.GetTypeNavBarSelection());
}
private void VerifyRightSelected(string expected)
{
Assert.Equal(expected, VisualStudio.Editor.GetMemberNavBarSelection());
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
public CSharpFrameDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
public CSharpFrameDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
[NonDefaultable]
internal readonly struct NextAlignTokensOperationAction
{
private readonly ImmutableArray<AbstractFormattingRule> _formattingRules;
private readonly int _index;
private readonly SyntaxNode _node;
private readonly List<AlignTokensOperation> _list;
public NextAlignTokensOperationAction(
ImmutableArray<AbstractFormattingRule> formattingRules,
int index,
SyntaxNode node,
List<AlignTokensOperation> list)
{
_formattingRules = formattingRules;
_index = index;
_node = node;
_list = list;
}
private NextAlignTokensOperationAction NextAction
=> new(_formattingRules, _index + 1, _node, _list);
public void Invoke()
{
// If we have no remaining handlers to execute, then we'll execute our last handler
if (_index >= _formattingRules.Length)
{
return;
}
else
{
// Call the handler at the index, passing a continuation that will come back to here with index + 1
_formattingRules[_index].AddAlignTokensOperations(_list, _node, NextAction);
return;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
[NonDefaultable]
internal readonly struct NextAlignTokensOperationAction
{
private readonly ImmutableArray<AbstractFormattingRule> _formattingRules;
private readonly int _index;
private readonly SyntaxNode _node;
private readonly List<AlignTokensOperation> _list;
public NextAlignTokensOperationAction(
ImmutableArray<AbstractFormattingRule> formattingRules,
int index,
SyntaxNode node,
List<AlignTokensOperation> list)
{
_formattingRules = formattingRules;
_index = index;
_node = node;
_list = list;
}
private NextAlignTokensOperationAction NextAction
=> new(_formattingRules, _index + 1, _node, _list);
public void Invoke()
{
// If we have no remaining handlers to execute, then we'll execute our last handler
if (_index >= _formattingRules.Length)
{
return;
}
else
{
// Call the handler at the index, passing a continuation that will come back to here with index + 1
_formattingRules[_index].AddAlignTokensOperations(_list, _node, NextAction);
return;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/ObjectBrowserWindow_InProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class ObjectBrowserWindow_InProc : InProcComponent
{
public static ObjectBrowserWindow_InProc Create() => new ObjectBrowserWindow_InProc();
public bool CloseWindow()
{
return InvokeOnUIThread(cancellationToken =>
{
var uiShell = GetGlobalService<SVsUIShell, IVsUIShell>();
if (ErrorHandler.Failed(uiShell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFrameOnly, new Guid(ToolWindowGuids.ObjectBrowser), out var frame)))
{
return false;
}
ErrorHandler.ThrowOnFailure(frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave));
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 Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class ObjectBrowserWindow_InProc : InProcComponent
{
public static ObjectBrowserWindow_InProc Create() => new ObjectBrowserWindow_InProc();
public bool CloseWindow()
{
return InvokeOnUIThread(cancellationToken =>
{
var uiShell = GetGlobalService<SVsUIShell, IVsUIShell>();
if (ErrorHandler.Failed(uiShell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFrameOnly, new Guid(ToolWindowGuids.ObjectBrowser), out var frame)))
{
return false;
}
ErrorHandler.ThrowOnFailure(frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave));
return true;
});
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/CSharp/Portable/CodeRefactorings/AddAwait/CSharpAddAwaitCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.AddAwait;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait
{
/// <summary>
/// This refactoring complements the AddAwait fixer. It allows adding `await` and `await ... .ConfigureAwait(false)` even there is no compiler error to trigger the fixer.
/// </summary>
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddAwait), Shared]
internal partial class CSharpAddAwaitCodeRefactoringProvider : AbstractAddAwaitCodeRefactoringProvider<ExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddAwaitCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Add_await;
protected override string GetTitleWithConfigureAwait()
=> CSharpFeaturesResources.Add_await_and_ConfigureAwaitFalse;
protected override bool IsInAsyncContext(SyntaxNode node)
{
foreach (var current in node.Ancestors())
{
switch (current.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
return ((AnonymousFunctionExpressionSyntax)current).AsyncKeyword != default;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)current).Modifiers.Any(SyntaxKind.AsyncKeyword);
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.AddAwait;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait
{
/// <summary>
/// This refactoring complements the AddAwait fixer. It allows adding `await` and `await ... .ConfigureAwait(false)` even there is no compiler error to trigger the fixer.
/// </summary>
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddAwait), Shared]
internal partial class CSharpAddAwaitCodeRefactoringProvider : AbstractAddAwaitCodeRefactoringProvider<ExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddAwaitCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Add_await;
protected override string GetTitleWithConfigureAwait()
=> CSharpFeaturesResources.Add_await_and_ConfigureAwaitFalse;
protected override bool IsInAsyncContext(SyntaxNode node)
{
foreach (var current in node.Ancestors())
{
switch (current.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
return ((AnonymousFunctionExpressionSyntax)current).AsyncKeyword != default;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)current).Modifiers.Any(SyntaxKind.AsyncKeyword);
}
}
return false;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[Fact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Compilation
var comp2 = (Compilation)CreateCompilation(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as INamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as IEventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as IPropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as IMethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as IPropertySymbol).Type;
ResolveAndVerifySymbol(member03, originalSymbols[0], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member01, originalSymbols[1], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member05, originalSymbols[2], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member02, originalSymbols[3], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member04, originalSymbols[4], comp1, SymbolKeyComparison.None);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IGoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IGoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var igoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/igoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/igoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Assembly
var comp2 = CreateCompilation(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.None);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.None);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.None);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.None);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.None);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.None);
}
#endregion
#region "Metadata vs. Metadata"
[Fact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = (Compilation)CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation 2 Assembly"
var comp40 = (Compilation)CreateCompilation(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as IMethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as IMethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as IMethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees.First());
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
foreach (var local in df.VariablesDeclared)
{
var localType = ((ILocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, mtsym20_1, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, mtsym20_2, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, mtsym20_3, comp20, SymbolKeyComparison.None);
}
}
}
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CGoo();
N20.IGoo igoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/igoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IGoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IGoo.Prop, CGoo.Prop, Event, Field, IGoo.This, CGoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as IPropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as IFieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as IPropertySymbol).Type, model, comp20);
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// explicit
IDisposable IGoo.Prop { get; set; }
Exception IGoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IGoo igoo = new N20::CGoo();
var local = /*<bind0>*/igoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/igoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CGoo.Prop, CGoo.This, IGoo.Prop, IGoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as IPropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IPropertySymbol).Type, model, comp20);
}
#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.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[Fact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Compilation
var comp2 = (Compilation)CreateCompilation(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as INamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as IEventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as IPropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as IMethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as IPropertySymbol).Type;
ResolveAndVerifySymbol(member03, originalSymbols[0], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member01, originalSymbols[1], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member05, originalSymbols[2], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member02, originalSymbols[3], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member04, originalSymbols[4], comp1, SymbolKeyComparison.None);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IGoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IGoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var igoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/igoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/igoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Assembly
var comp2 = CreateCompilation(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.None);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.None);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.None);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.None);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.None);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.None);
}
#endregion
#region "Metadata vs. Metadata"
[Fact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = (Compilation)CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation 2 Assembly"
var comp40 = (Compilation)CreateCompilation(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as IMethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as IMethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as IMethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees.First());
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
foreach (var local in df.VariablesDeclared)
{
var localType = ((ILocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, mtsym20_1, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, mtsym20_2, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, mtsym20_3, comp20, SymbolKeyComparison.None);
}
}
}
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CGoo();
N20.IGoo igoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/igoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IGoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IGoo.Prop, CGoo.Prop, Event, Field, IGoo.This, CGoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as IPropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as IFieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as IPropertySymbol).Type, model, comp20);
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// explicit
IDisposable IGoo.Prop { get; set; }
Exception IGoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IGoo igoo = new N20::CGoo();
var local = /*<bind0>*/igoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/igoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CGoo.Prop, CGoo.This, IGoo.Prop, IGoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as IPropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IPropertySymbol).Type, model, comp20);
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/CSharp/Test/Symbol/Symbols/AnonymousTypesSymbolTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class AnonymousTypesSymbolTests : CompilingTestBase
{
[ClrOnlyFact]
public void AnonymousTypeSymbol_InQuery()
{
var source = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> r1 =
from int x in c1
let g = x * 10
let z = g + x*100
select x + z;
System.Console.WriteLine(r1);
}
}
";
var verifier = CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "x", "g" } },
new TypeDescr() { FieldNames = new string[] { "<>h__TransparentIdentifier0", "z" } }
)
);
TestAnonymousTypeFieldSymbols_InQuery(verifier.EmittedAssemblyData);
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_Mix()
{
var source = @"
using System;
namespace Test
{
class Program
{
static int Main()
{
int result = 0;
var a0 = new { b1 = true, b2 = false };
var a1 = new
{
b1 = 0123456789,
b2 = 1234567890U,
b3 = 2345678901u,
b4 = 3456789012L,
b5 = 4567890123l,
b6 = 5678901234UL,
b7 = 6789012345Ul,
b8 = 7890123456uL,
b9 = 8901234567ul,
b10 = 9012345678LU,
b11 = 9123456780Lu,
b12 = 1234567809lU,
b13 = 2345678091lu
};
return result;
}
}
}
";
CompileAndVerify(source);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
return (Func<object>) (() => new { x2 });
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty2()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
Func<object> x3 = () => new { x2 };
return x3;
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty3()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>());
Console.WriteLine(Goo<string>());
Console.WriteLine(Goo<int?>());
}
static object Goo<T>()
{
T x2 = default(T);
return new { x2 };
}
}";
CompileAndVerify(
source,
expectedOutput:
@"{ x2 = 0 }
{ x2 = }
{ x2 = }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty4()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
foreach(var x in Goo<int>())
{
Console.Write(x);
}
}
static IEnumerable<object> Goo<T>()
{
T x2 = default(T);
yield return new { x2 }.ToString();
yield return new { YYY = default(T), z = new { field = x2 } };
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }{ YYY = 0, z = { field = 0 } }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_Empty()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
return (Func<object>) (() => new { });
}
}";
CompileAndVerify(
source,
expectedOutput: "{ }"
);
}
#region AnonymousTypeSymbol_InQuery :: Checking fields via reflection
private void TestAnonymousTypeFieldSymbols_InQuery(ImmutableArray<byte> image)
{
Assembly refAsm = Assembly.Load(image.ToArray());
Type type = refAsm.GetType("<>f__AnonymousType0`2");
Assert.NotNull(type);
Assert.Equal(2, type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Count());
CheckField(type.GetField("<x>i__Field", BindingFlags.NonPublic | BindingFlags.Instance), type.GetGenericArguments()[0]);
CheckField(type.GetField("<g>i__Field", BindingFlags.NonPublic | BindingFlags.Instance), type.GetGenericArguments()[1]);
}
private void CheckField(FieldInfo field, Type fieldType)
{
Assert.NotNull(field);
Assert.NotNull(fieldType);
Assert.Equal(fieldType, field.FieldType);
Assert.Equal(FieldAttributes.Private | FieldAttributes.InitOnly, field.Attributes);
var attrs = field.CustomAttributes.ToList();
Assert.Equal(1, attrs.Count);
Assert.Equal(typeof(DebuggerBrowsableAttribute), attrs[0].AttributeType);
var args = attrs[0].ConstructorArguments.ToArray();
Assert.Equal(1, args.Length);
Assert.Equal(typeof(DebuggerBrowsableState), args[0].ArgumentType);
Assert.Equal(DebuggerBrowsableState.Never, (DebuggerBrowsableState)args[0].Value);
}
#endregion
[ClrOnlyFact]
public void AnonymousTypeSymbol_Simple()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { a = 1, b = 2 };
object at2 = new { (new string[2]).Length, at1, C = new Object() };
object at3 = new { a = '1', b = at1 };
PrintFields(at1.GetType());
PrintFields(at2.GetType());
PrintFields(at3.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "a", "b" } },
new TypeDescr() { FieldNames = new string[] { "Length", "at1", "C" } }
),
expectedOutput: @"
<>f__AnonymousType0`2:
Private, InitOnly Int32 <a>i__Field
Private, InitOnly Int32 <b>i__Field
<>f__AnonymousType1`3:
Private, InitOnly Int32 <Length>i__Field
Private, InitOnly <>f__AnonymousType0`2 <at1>i__Field
Private, InitOnly Object <C>i__Field
<>f__AnonymousType0`2:
Private, InitOnly Char <a>i__Field
Private, InitOnly <>f__AnonymousType0`2 <b>i__Field
"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>..ctor(<Length>j__TPar, <at1>j__TPar, <C>j__TPar)",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_000d: ldarg.0
IL_000e: ldarg.2
IL_000f: stfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0014: ldarg.0
IL_0015: ldarg.3
IL_0016: stfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_001b: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.Length.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.at1.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.C.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.Equals",
@"{
// Code size 89 (0x59)
.maxstack 3
.locals init (<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar> V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0057
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0055
IL_000e: call ""System.Collections.Generic.EqualityComparer<<Length>j__TPar> System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Default.get""
IL_0013: ldarg.0
IL_0014: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0019: ldloc.0
IL_001a: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_001f: callvirt ""bool System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Equals(<Length>j__TPar, <Length>j__TPar)""
IL_0024: brfalse.s IL_0055
IL_0026: call ""System.Collections.Generic.EqualityComparer<<at1>j__TPar> System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Default.get""
IL_002b: ldarg.0
IL_002c: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0031: ldloc.0
IL_0032: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0037: callvirt ""bool System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Equals(<at1>j__TPar, <at1>j__TPar)""
IL_003c: brfalse.s IL_0055
IL_003e: call ""System.Collections.Generic.EqualityComparer<<C>j__TPar> System.Collections.Generic.EqualityComparer<<C>j__TPar>.Default.get""
IL_0043: ldarg.0
IL_0044: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0049: ldloc.0
IL_004a: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_004f: callvirt ""bool System.Collections.Generic.EqualityComparer<<C>j__TPar>.Equals(<C>j__TPar, <C>j__TPar)""
IL_0054: ret
IL_0055: ldc.i4.0
IL_0056: ret
IL_0057: ldc.i4.1
IL_0058: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.GetHashCode",
@"{
// Code size 75 (0x4b)
.maxstack 3
IL_0000: ldc.i4 " + GetHashCodeInitialValue("<Length>i__Field", "<at1>i__Field", "<C>i__Field") + @"
IL_0005: ldc.i4 0xa5555529
IL_000a: mul
IL_000b: call ""System.Collections.Generic.EqualityComparer<<Length>j__TPar> System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Default.get""
IL_0010: ldarg.0
IL_0011: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0016: callvirt ""int System.Collections.Generic.EqualityComparer<<Length>j__TPar>.GetHashCode(<Length>j__TPar)""
IL_001b: add
IL_001c: ldc.i4 0xa5555529
IL_0021: mul
IL_0022: call ""System.Collections.Generic.EqualityComparer<<at1>j__TPar> System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Default.get""
IL_0027: ldarg.0
IL_0028: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_002d: callvirt ""int System.Collections.Generic.EqualityComparer<<at1>j__TPar>.GetHashCode(<at1>j__TPar)""
IL_0032: add
IL_0033: ldc.i4 0xa5555529
IL_0038: mul
IL_0039: call ""System.Collections.Generic.EqualityComparer<<C>j__TPar> System.Collections.Generic.EqualityComparer<<C>j__TPar>.Default.get""
IL_003e: ldarg.0
IL_003f: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0044: callvirt ""int System.Collections.Generic.EqualityComparer<<C>j__TPar>.GetHashCode(<C>j__TPar)""
IL_0049: add
IL_004a: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.ToString",
@"{
// Code size 138 (0x8a)
.maxstack 7
.locals init (<Length>j__TPar V_0,
<at1>j__TPar V_1,
<C>j__TPar V_2)
IL_0000: ldnull
IL_0001: ldstr ""{{ Length = {0}, at1 = {1}, C = {2} }}""
IL_0006: ldc.i4.3
IL_0007: newarr ""object""
IL_000c: dup
IL_000d: ldc.i4.0
IL_000e: ldarg.0
IL_000f: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: dup
IL_0018: ldobj ""<Length>j__TPar""
IL_001d: box ""<Length>j__TPar""
IL_0022: brtrue.s IL_0028
IL_0024: pop
IL_0025: ldnull
IL_0026: br.s IL_0033
IL_0028: constrained. ""<Length>j__TPar""
IL_002e: callvirt ""string object.ToString()""
IL_0033: stelem.ref
IL_0034: dup
IL_0035: ldc.i4.1
IL_0036: ldarg.0
IL_0037: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: dup
IL_0040: ldobj ""<at1>j__TPar""
IL_0045: box ""<at1>j__TPar""
IL_004a: brtrue.s IL_0050
IL_004c: pop
IL_004d: ldnull
IL_004e: br.s IL_005b
IL_0050: constrained. ""<at1>j__TPar""
IL_0056: callvirt ""string object.ToString()""
IL_005b: stelem.ref
IL_005c: dup
IL_005d: ldc.i4.2
IL_005e: ldarg.0
IL_005f: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: dup
IL_0068: ldobj ""<C>j__TPar""
IL_006d: box ""<C>j__TPar""
IL_0072: brtrue.s IL_0078
IL_0074: pop
IL_0075: ldnull
IL_0076: br.s IL_0083
IL_0078: constrained. ""<C>j__TPar""
IL_007e: callvirt ""string object.ToString()""
IL_0083: stelem.ref
IL_0084: call ""string string.Format(System.IFormatProvider, string, params object[])""
IL_0089: ret
}"
);
}
[Fact]
public void AnonymousTypeSymbol_Simple_Threadsafety()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { a = 1, b = 2 };
var at2 = new { a = 1, b = 2, c = 3};
var at3 = new { a = 1, b = 2, c = 3, d = 4};
var at4 = new { a = 1, b = 2, c = 3, d = 4, e = 5};
var at5 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at6 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at7 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at8 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at9 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at11 = new { aa = 1, b = 2 };
var at12 = new { aa = 1, b = 2, c = 3};
var at13 = new { aa = 1, b = 2, c = 3, d = 4};
var at14 = new { aa = 1, b = 2, c = 3, d = 4, e = 5};
var at15 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at16 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at17 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at18 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at19 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at21 = new { ba = 1, b = 2 };
var at22 = new { ba = 1, b = 2, c = 3};
var at23 = new { ba = 1, b = 2, c = 3, d = 4};
var at24 = new { ba = 1, b = 2, c = 3, d = 4, e = 5};
var at25 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at26 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at27 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at28 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at29 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at31 = new { ca = 1, b = 2 };
var at32 = new { ca = 1, b = 2, c = 3};
var at33 = new { ca = 1, b = 2, c = 3, d = 4};
var at34 = new { ca = 1, b = 2, c = 3, d = 4, e = 5};
var at35 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at36 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at37 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at38 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at39 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at41 = new { da = 1, b = 2 };
var at42 = new { da = 1, b = 2, c = 3};
var at43 = new { da = 1, b = 2, c = 3, d = 4};
var at44 = new { da = 1, b = 2, c = 3, d = 4, e = 5};
var at45 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at46 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at47 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at48 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at49 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
PrintFields(at1.GetType());
PrintFields(at2.GetType());
PrintFields(at3.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
for (int i = 0; i < 100; i++)
{
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
var tasks = new Task[10];
for (int j = 0; j < tasks.Length; j++)
{
var metadataOnly = j % 2 == 0;
tasks[j] = Task.Run(() =>
{
var stream = new MemoryStream();
var result = compilation.Emit(stream, options: new EmitOptions(metadataOnly: metadataOnly));
result.Diagnostics.Verify();
});
}
// this should not fail. if you ever see a NRE or some kind of crash here enter a bug.
// it may be reproducing just once in a while, in Release only...
// it is still a bug.
Task.WaitAll(tasks);
}
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_Empty()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { };
var at2 = new { };
at2 = at1;
string x = at1.ToString() + at2.ToString();
PrintFields(at1.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { } }
),
expectedOutput: @"
<>f__AnonymousType0:
"
).VerifyIL(
"<>f__AnonymousType0..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0.Equals",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init (<>f__AnonymousType0 V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType0""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0010
IL_000b: ldloc.0
IL_000c: ldnull
IL_000d: cgt.un
IL_000f: ret
IL_0010: ldc.i4.1
IL_0011: ret
}"
).VerifyIL(
"<>f__AnonymousType0.GetHashCode",
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}"
).VerifyIL(
"<>f__AnonymousType0.ToString",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""{ }""
IL_0005: ret
}"
);
}
[WorkItem(543022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543022")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_StandardNames()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { GetHashCode = new { } };
Console.Write(at1.GetType());
Console.Write(""-"");
Console.Write(at1.GetHashCode.GetType());
}
}
";
CompileAndVerify(
source,
expectedOutput: "<>f__AnonymousType0`1[<>f__AnonymousType1]-<>f__AnonymousType1");
}
[WorkItem(543022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543022")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_StandardNames2()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { ToString = ""Field"" };
Console.Write(at1.ToString());
Console.Write(""-"");
Console.Write(at1.ToString);
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ ToString = Field }-Field");
}
[Fact]
public void AnonymousTypeSymbol_StandardNames3()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { ToString = 1, Equals = new Object(), GetHashCode = ""GetHashCode"" };
PrintFields(at1.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "ToString", "Equals", "GetHashCode" } }
),
expectedOutput: @"
<>f__AnonymousType0`3:
Private, InitOnly Int32 <ToString>i__Field
Private, InitOnly Object <Equals>i__Field
Private, InitOnly String <GetHashCode>i__Field
"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>..ctor",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_000d: ldarg.0
IL_000e: ldarg.2
IL_000f: stfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0014: ldarg.0
IL_0015: ldarg.3
IL_0016: stfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_001b: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.Equals",
@"{
// Code size 89 (0x59)
.maxstack 3
.locals init (<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar> V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0057
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0055
IL_000e: call ""System.Collections.Generic.EqualityComparer<<ToString>j__TPar> System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Default.get""
IL_0013: ldarg.0
IL_0014: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0019: ldloc.0
IL_001a: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_001f: callvirt ""bool System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Equals(<ToString>j__TPar, <ToString>j__TPar)""
IL_0024: brfalse.s IL_0055
IL_0026: call ""System.Collections.Generic.EqualityComparer<<Equals>j__TPar> System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Default.get""
IL_002b: ldarg.0
IL_002c: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0031: ldloc.0
IL_0032: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0037: callvirt ""bool System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Equals(<Equals>j__TPar, <Equals>j__TPar)""
IL_003c: brfalse.s IL_0055
IL_003e: call ""System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar> System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Default.get""
IL_0043: ldarg.0
IL_0044: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0049: ldloc.0
IL_004a: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_004f: callvirt ""bool System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Equals(<GetHashCode>j__TPar, <GetHashCode>j__TPar)""
IL_0054: ret
IL_0055: ldc.i4.0
IL_0056: ret
IL_0057: ldc.i4.1
IL_0058: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.GetHashCode",
@"{
// Code size 75 (0x4b)
.maxstack 3
IL_0000: ldc.i4 0x3711624
IL_0005: ldc.i4 0xa5555529
IL_000a: mul
IL_000b: call ""System.Collections.Generic.EqualityComparer<<ToString>j__TPar> System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Default.get""
IL_0010: ldarg.0
IL_0011: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0016: callvirt ""int System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.GetHashCode(<ToString>j__TPar)""
IL_001b: add
IL_001c: ldc.i4 0xa5555529
IL_0021: mul
IL_0022: call ""System.Collections.Generic.EqualityComparer<<Equals>j__TPar> System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Default.get""
IL_0027: ldarg.0
IL_0028: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_002d: callvirt ""int System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.GetHashCode(<Equals>j__TPar)""
IL_0032: add
IL_0033: ldc.i4 0xa5555529
IL_0038: mul
IL_0039: call ""System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar> System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Default.get""
IL_003e: ldarg.0
IL_003f: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0044: callvirt ""int System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.GetHashCode(<GetHashCode>j__TPar)""
IL_0049: add
IL_004a: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.ToString",
@"{
// Code size 138 (0x8a)
.maxstack 7
.locals init (<ToString>j__TPar V_0,
<Equals>j__TPar V_1,
<GetHashCode>j__TPar V_2)
IL_0000: ldnull
IL_0001: ldstr ""{{ ToString = {0}, Equals = {1}, GetHashCode = {2} }}""
IL_0006: ldc.i4.3
IL_0007: newarr ""object""
IL_000c: dup
IL_000d: ldc.i4.0
IL_000e: ldarg.0
IL_000f: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: dup
IL_0018: ldobj ""<ToString>j__TPar""
IL_001d: box ""<ToString>j__TPar""
IL_0022: brtrue.s IL_0028
IL_0024: pop
IL_0025: ldnull
IL_0026: br.s IL_0033
IL_0028: constrained. ""<ToString>j__TPar""
IL_002e: callvirt ""string object.ToString()""
IL_0033: stelem.ref
IL_0034: dup
IL_0035: ldc.i4.1
IL_0036: ldarg.0
IL_0037: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: dup
IL_0040: ldobj ""<Equals>j__TPar""
IL_0045: box ""<Equals>j__TPar""
IL_004a: brtrue.s IL_0050
IL_004c: pop
IL_004d: ldnull
IL_004e: br.s IL_005b
IL_0050: constrained. ""<Equals>j__TPar""
IL_0056: callvirt ""string object.ToString()""
IL_005b: stelem.ref
IL_005c: dup
IL_005d: ldc.i4.2
IL_005e: ldarg.0
IL_005f: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: dup
IL_0068: ldobj ""<GetHashCode>j__TPar""
IL_006d: box ""<GetHashCode>j__TPar""
IL_0072: brtrue.s IL_0078
IL_0074: pop
IL_0075: ldnull
IL_0076: br.s IL_0083
IL_0078: constrained. ""<GetHashCode>j__TPar""
IL_007e: callvirt ""string object.ToString()""
IL_0083: stelem.ref
IL_0084: call ""string string.Format(System.IFormatProvider, string, params object[])""
IL_0089: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.ToString.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.Equals.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.GetHashCode.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0006: ret
}"
);
}
#region "Utility methods"
/// <summary>
/// This method duplicates the generation logic for initial value used
/// in anonymous type's GetHashCode function
/// </summary>
public static string GetHashCodeInitialValue(params string[] names)
{
const int HASH_FACTOR = -1521134295; // (int)0xa5555529
int init = 0;
foreach (var name in names)
{
init = unchecked(init * HASH_FACTOR + Hash.GetFNVHashCode(name));
}
return "0x" + init.ToString("X").ToLower();
}
private struct TypeDescr
{
public string[] FieldNames;
}
private void TestAnonymousTypeSymbols(ModuleSymbol module, params TypeDescr[] typeDescrs)
{
int cnt = typeDescrs.Length;
Assert.Equal(0, module.GlobalNamespace.GetMembers("<>f__AnonymousType" + cnt.ToString()).Length);
// test template classes
for (int i = 0; i < cnt; i++)
{
TestAnonymousType(module.GlobalNamespace.GetMember<NamedTypeSymbol>("<>f__AnonymousType" + i.ToString()), i, typeDescrs[i]);
}
}
private void TestAnonymousType(NamedTypeSymbol type, int typeIndex, TypeDescr typeDescr)
{
Assert.NotEqual(default, typeDescr);
Assert.NotNull(typeDescr.FieldNames);
// prepare
int fieldsCount = typeDescr.FieldNames.Length;
string[] genericParameters = new string[fieldsCount];
string genericParametersList = null;
for (int i = 0; i < fieldsCount; i++)
{
genericParameters[i] = String.Format("<{0}>j__TPar", typeDescr.FieldNames[i]);
genericParametersList = genericParametersList == null
? genericParameters[i]
: genericParametersList + ", " + genericParameters[i];
}
string genericParametersSuffix = fieldsCount == 0 ? "" : "<" + genericParametersList + ">";
string typeViewName = String.Format("<>f__AnonymousType{0}{1}", typeIndex.ToString(), genericParametersSuffix);
// test
Assert.Equal(typeViewName, type.ToDisplayString());
Assert.Equal("object", type.BaseType().ToDisplayString());
Assert.True(fieldsCount == 0 ? !type.IsGenericType : type.IsGenericType);
Assert.Equal(fieldsCount, type.Arity);
Assert.Equal(Accessibility.Internal, type.DeclaredAccessibility);
Assert.True(type.IsSealed);
Assert.False(type.IsStatic);
Assert.Equal(0, type.Interfaces().Length);
// test non-existing members
Assert.Equal(0, type.GetMembers("doesnotexist").Length);
TestAttributeOnSymbol(
type,
new AttributeInfo
{
CtorName = "System.Runtime.CompilerServices.CompilerGeneratedAttribute.CompilerGeneratedAttribute()",
ConstructorArguments = new string[] { }
}
);
// test properties
for (int i = 0; i < fieldsCount; i++)
{
var typeParameter = type.TypeParameters[i];
Assert.Equal(genericParameters[i], typeParameter.ToDisplayString());
TestAnonymousTypeProperty(type, typeViewName, typeDescr.FieldNames[i], typeParameter);
}
// methods
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, ".ctor"),
String.Format("{0}.<>f__AnonymousType{1}({2})", typeViewName, typeIndex.ToString(), genericParametersList),
"void",
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "Equals"),
String.Format("{0}.Equals(object)", typeViewName),
"bool",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "GetHashCode"),
String.Format("{0}.GetHashCode()", typeViewName),
"int",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "ToString"),
String.Format("{0}.ToString()", typeViewName),
"string",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
}
private T GetMemberByName<T>(NamedTypeSymbol type, string name) where T : Symbol
{
foreach (var symbol in type.GetMembers(name))
{
if (symbol is T)
{
return (T)symbol;
}
}
return null;
}
private void TestAnonymousTypeProperty(NamedTypeSymbol type, string typeViewName, string name, TypeSymbol propType)
{
PropertySymbol property = this.GetMemberByName<PropertySymbol>(type, name);
Assert.NotNull(property);
Assert.Equal(propType, property.Type);
Assert.Equal(Accessibility.Public, property.DeclaredAccessibility);
Assert.False(property.IsAbstract);
Assert.False(property.IsIndexer);
Assert.False(property.IsOverride);
Assert.True(property.IsReadOnly);
Assert.False(property.IsStatic);
Assert.False(property.IsSealed);
Assert.False(property.IsVirtual);
Assert.False(property.IsWriteOnly);
var getter = property.GetMethod;
Assert.NotNull(getter);
Assert.Equal("get_" + name, getter.Name);
CheckMethodSymbol(
getter,
typeViewName + "." + name + ".get",
propType.ToDisplayString()
);
}
private void CheckMethodSymbol(
MethodSymbol method,
string signature,
string retType,
bool isVirtualAndOverride = false,
AttributeInfo attr = null
)
{
Assert.NotNull(method);
Assert.Equal(signature, method.ToDisplayString());
Assert.Equal(Accessibility.Public, method.DeclaredAccessibility);
Assert.False(method.IsAbstract);
Assert.Equal(isVirtualAndOverride, method.IsOverride);
Assert.False(method.IsStatic);
Assert.False(method.IsSealed);
Assert.False(method.IsVararg);
Assert.False(method.IsVirtual);
Assert.Equal(isVirtualAndOverride, method.IsMetadataVirtual());
Assert.Equal(retType, method.ReturnTypeWithAnnotations.ToDisplayString());
TestAttributeOnSymbol(method, attr == null ? new AttributeInfo[] { } : new AttributeInfo[] { attr });
}
private class AttributeInfo
{
public string CtorName;
public string[] ConstructorArguments;
}
private void TestAttributeOnSymbol(Symbol symbol, params AttributeInfo[] attributes)
{
var actual = symbol.GetAttributes();
Assert.Equal(attributes.Length, actual.Length);
for (int index = 0; index < attributes.Length; index++)
{
var attr = attributes[index];
Assert.Equal(attr.CtorName, actual[index].AttributeConstructor.ToDisplayString());
Assert.Equal(attr.ConstructorArguments.Length, actual[index].CommonConstructorArguments.Length);
for (int argIndex = 0; argIndex < attr.ConstructorArguments.Length; argIndex++)
{
Assert.Equal(
attr.ConstructorArguments[argIndex],
actual[index].CommonConstructorArguments[argIndex].Value.ToString()
);
}
}
}
#endregion
[ClrOnlyFact]
public void AnonymousType_BaseAccess()
{
var source = @"
using System;
class Base
{
protected int field = 123;
}
class Derived: Base
{
public static void Main(string[] args)
{
(new Derived()).Test();
}
public void Test()
{
var a = new { base.field };
Console.WriteLine(a.ToString());
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ field = 123 }");
}
[ClrOnlyFact]
public void AnonymousType_PropertyAccess()
{
var source = @"
using System;
class Class1
{
public static void Main(string[] args)
{
var a = new { (new Class1()).PropertyA };
Console.WriteLine(a.ToString());
}
public string PropertyA
{
get { return ""pa-value""; }
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ PropertyA = pa-value }");
}
[ClrOnlyFact]
public void AnonymousType_Simple()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
int a = (new {a = 1, b=""text"", }).a;
string b = (new {a = 1, b=""text""}).b;
Console.WriteLine(string.Format(""a={0}; b={1}"", a, b));
}
}
";
CompileAndVerify(
source,
expectedOutput: "a=1; b=text");
}
[ClrOnlyFact]
public void AnonymousType_CustModifiersOnPropertyFields()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var intArrMod = Modifiers.F9();
var at1 = new { f = intArrMod };
var at2 = new { f = new int[] {} };
at1 = at2;
at2 = at1;
}
}
";
CompileAndVerify(
source,
references: new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll });
}
[ClrOnlyFact]
public void AnonymousType_ToString()
{
// test AnonymousType.ToString()
using (new EnsureInvariantCulture())
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
Console.WriteLine((new { a = 1, b=""text"", c=123.456}).ToString());
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ a = 1, b = text, c = 123.456 }");
}
}
[ClrOnlyFact]
public void AnonymousType_Equals()
{
var source = @"
using System;
using System.Collections.Generic;
struct S: IEquatable<S>
{
public int X;
public int Y;
public S(int x, int y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return string.Format(""({0}, {1})"", this.X, this.Y);
}
public bool Equals(S other)
{
bool equals = this.X == other.X && this.Y == other.Y;
this.X = other.X = -1;
this.Y = other.Y = -1;
return equals;
}
}
class Query
{
public static void Main(string[] args)
{
Compare(new { a = new S(1, 2), b = new S(1, 2) }, new { a = new S(1, 2), b = new S(1, 2) });
Compare(new { a = new S(1, 2), b = new S(1, 2) }, new { b = new S(1, 2), a = new S(1, 2) });
object a = new { a = new S(1, 2) };
Compare(a, new { a = new S(1, 2) });
Compare(a, new { a = new S(-1, -1) });
Compare(new { a = new S(1, 2) }, a);
Compare(new { a = new S(-1, -1) }, a);
}
public static void Compare(object a, object b)
{
Console.WriteLine(string.Format(""{0}.Equals({1}) = {2}"", a.ToString(), b.ToString(), a.Equals(b).ToString()));
}
}";
CompileAndVerify(
source,
expectedOutput: @"
{ a = (1, 2), b = (1, 2) }.Equals({ a = (1, 2), b = (1, 2) }) = True
{ a = (1, 2), b = (1, 2) }.Equals({ b = (1, 2), a = (1, 2) }) = False
{ a = (1, 2) }.Equals({ a = (1, 2) }) = True
{ a = (1, 2) }.Equals({ a = (-1, -1) }) = False
{ a = (1, 2) }.Equals({ a = (1, 2) }) = True
{ a = (-1, -1) }.Equals({ a = (1, 2) }) = False
");
}
[ClrOnlyFact]
public void AnonymousType_GetHashCode()
{
var source = @"
using System;
struct S
{
public int X;
public int Y;
public S(int x, int y)
{
this.X = x;
this.Y = y;
}
public override bool Equals(object obj)
{
throw new Exception();
}
public override int GetHashCode()
{
return this.X + this.Y;
}
public override string ToString()
{
return string.Format(""({0}, {1})"", this.X, this.Y);
}
}
class Query
{
public static void Main(string[] args)
{
Print(new { }, new S(0, 0));
Print(new { a = new S(2, 2), b = new S(1, 2) }, new { a = new S(4, 0), b = new S(2, 1) });
Print(new { a = new S(4, 0), b = new S(2, 1) }, new { b = new S(4, 0), a = new S(2, 1) });
}
public static void Print(object a, object b)
{
Console.WriteLine(string.Format(""{0}.GetHashCode() == {1}.GetHashCode() = {2}"", a.ToString(), b.ToString(), a.GetHashCode() == b.GetHashCode()));
}
}
";
CompileAndVerify(
source,
expectedOutput: @"
{ }.GetHashCode() == (0, 0).GetHashCode() = True
{ a = (2, 2), b = (1, 2) }.GetHashCode() == { a = (4, 0), b = (2, 1) }.GetHashCode() = True
{ a = (4, 0), b = (2, 1) }.GetHashCode() == { b = (4, 0), a = (2, 1) }.GetHashCode() = False
");
}
[ClrOnlyFact]
public void AnonymousType_MultiplyEmitDoesNotChangeTheOrdering()
{
// this test checks whether or not anonymous types which came from speculative
// semantic API have any effect on the anonymous types emitted and
// whether or not the order is still the same across several emits
var source1 = @"
using System;
class Class2
{
public static void Main2()
{
var d = new { args = 0 };
var b = new { a = """", b = 1 };
}
}
";
var source2 = @"
using System;
class Class1
{
public static void Main(string[] args)
{
var a = new { };
var b = new { a = """", b = 1 };
var c = new { b = 1, a = .2 };
var d = new { args };
}
}
";
var source3 = @"
using System;
class Class3
{
public static void Main2()
{
var c = new { b = 1, a = .2 };
var a = new { };
}
}
";
var compilation = CreateCompilationWithMscorlib40(new string[] { source1, source2, source3 }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), parseOptions: TestOptions.Regular);
for (int i = 0; i < 10; i++)
{
this.CompileAndVerify(
compilation,
symbolValidator: module =>
{
var types = module.GlobalNamespace.GetTypeMembers()
.Where(t => t.Name.StartsWith("<>", StringComparison.Ordinal))
.Select(t => t.ToDisplayString())
.OrderBy(t => t)
.ToArray();
Assert.Equal(4, types.Length);
Assert.Equal("<>f__AnonymousType0<<args>j__TPar>", types[0]);
Assert.Equal("<>f__AnonymousType1<<a>j__TPar, <b>j__TPar>", types[1]);
Assert.Equal("<>f__AnonymousType2", types[2]);
Assert.Equal("<>f__AnonymousType3<<b>j__TPar, <a>j__TPar>", types[3]);
},
verify: Verification.Passes
);
// do some speculative semantic query
var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]);
var position = source1.IndexOf("var d", StringComparison.Ordinal) - 1;
var expr1 = SyntaxFactory.ParseExpression("new { x = 1, y" + i.ToString() + " = \"---\" }");
var info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(info1.Type);
}
}
[WorkItem(543134, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543134")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_Simple_1()
{
var source = @"
class Test
{
public static void Main()
{
var a = new { };
var b = new { p1 = 10 };
}
}
";
CompileAndVerify(source);
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_NamesConflictInsideLambda()
{
var source = @"
using System;
class Test
{
public static void Main()
{
M(123);
}
public static void M<T>(T p)
{
Action a = () => { Console.Write(new { x = 1221, get_x = p }.x.ToString()); };
a();
}
}
";
CompileAndVerify(source, expectedOutput: "1221");
}
[WorkItem(543693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543693")]
[ClrOnlyFact]
public void Bug11593a()
{
var source = @"
delegate T Func<A0, T>(A0 a0);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public Y<T> Select<T>(Func<U, T> selector)
{
return new Y<T>(selector(u));
}
}
class P
{
static void Main()
{
var src = new Y<int>(2);
var q = from x in src
let y = x + 3
select new { X = x, Y = y };
if ((q.u.X != 2 || q.u.Y != 5))
{
}
System.Console.WriteLine(""Success"");
}
}
";
CompileAndVerify(source, expectedOutput: "Success");
}
[WorkItem(543693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543693")]
[ClrOnlyFact]
public void Bug11593b()
{
var source = @"
delegate T Func<A0, T>(A0 a0);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public Y<T> Select<T>(Func<U, T> selector)
{
return new Y<T>(selector(u));
}
}
class P
{
static void Main()
{
var xxx = new { X = 1, Y = 2 };
var src = new Y<int>(2);
var q = from x in src
let y = x + 3
select new { X = x, Y = y };
if ((q.u.X != 2 || q.u.Y != 5))
{
}
System.Console.WriteLine(""Success"");
}
}
";
CompileAndVerify(source, expectedOutput: "Success");
}
[WorkItem(543177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543177")]
[ClrOnlyFact]
public void AnonymousTypePropertyValueWithWarning()
{
var source = @"
using System;
class Program
{
static void Main()
{
var a1 = new
{
p1 = 0123456789L,
p2 = 0123456789l, // Warning CS0078
};
Console.Write(a1.p1 == a1.p2);
}
}
";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact(), WorkItem(544323, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544323")]
public void AnonymousTypeAndMemberSymbolsLocations()
{
var source = @"
using System;
class Program
{
static void Main()
{
var an = new { id = 1, name = ""QC"" };
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single();
var sym = model.GetSymbolInfo(expr);
Assert.NotNull(sym.Symbol);
Assert.True(sym.Symbol.GetSymbol().IsFromCompilation(comp), "IsFromCompilation");
Assert.False(sym.Symbol.Locations.IsEmpty, "Symbol Location");
Assert.True(sym.Symbol.Locations[0].IsInSource);
var info = model.GetTypeInfo(expr);
Assert.NotNull(info.Type);
var mems = info.Type.GetMembers();
foreach (var m in mems)
{
Assert.True(m.GetSymbol().IsFromCompilation(comp), "IsFromCompilation");
Assert.False(m.Locations.IsEmpty, String.Format("No Location: {0}", m));
Assert.True(m.Locations[0].IsInSource);
}
}
[Fact]
public void SameAnonymousTypeInTwoLocations()
{
// This code declares the same anonymous type twice. Make sure the locations
// reflect this.
var source = @"
using System;
class Program
{
static void Main()
{
var a1 = new { id = 1, name = ""QC"" };
var a2 = new { id = 1, name = ""QC"" };
var a3 = a1;
var a4 = a2;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var programType = (NamedTypeSymbol)(comp.GlobalNamespace.GetTypeMembers("Program").Single());
var mainMethod = (MethodSymbol)(programType.GetMembers("Main").Single());
var mainSyntax = mainMethod.DeclaringSyntaxReferences.Single().GetSyntax() as MethodDeclarationSyntax;
var mainBlock = mainSyntax.Body;
var statement1 = mainBlock.Statements[0] as LocalDeclarationStatementSyntax;
var statement2 = mainBlock.Statements[1] as LocalDeclarationStatementSyntax;
var statement3 = mainBlock.Statements[2] as LocalDeclarationStatementSyntax;
var statement4 = mainBlock.Statements[3] as LocalDeclarationStatementSyntax;
var localA3 = model.GetDeclaredSymbol(statement3.Declaration.Variables[0]) as ILocalSymbol;
var localA4 = model.GetDeclaredSymbol(statement4.Declaration.Variables[0]) as ILocalSymbol;
var typeA3 = localA3.Type;
var typeA4 = localA4.Type;
// A3 and A4 should have different type objects, that compare equal. They should have
// different locations.
Assert.Equal(typeA3, typeA4);
Assert.NotSame(typeA3, typeA4);
Assert.NotEqual(typeA3.Locations[0], typeA4.Locations[0]);
// The locations of a3's type should be the type declared in statement 1, the location
// of a4's type should be the type declared in statement 2.
Assert.True(statement1.Span.Contains(typeA3.Locations[0].SourceSpan));
Assert.True(statement2.Span.Contains(typeA4.Locations[0].SourceSpan));
}
private static readonly SyntaxTree s_equalityComparerSourceTree = Parse(@"
namespace System.Collections
{
public interface IEqualityComparer
{
bool Equals(object x, object y);
int GetHashCode(object obj);
}
}
namespace System.Collections.Generic
{
public interface IEqualityComparer<T>
{
bool Equals(T x, T y);
int GetHashCode(T obj);
}
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
protected EqualityComparer() { }
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
bool IEqualityComparer.Equals(object x, object y) { return true; }
int IEqualityComparer.GetHashCode(object obj) { return 0; }
// Properties
public static EqualityComparer<T> Default { get { return null; } }
}
}
");
/// <summary>
/// Bug#15914: Breaking Changes
/// </summary>
[Fact, WorkItem(530365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530365")]
public void NoStdLibNoEmitToStringForAnonymousType()
{
var source = @"
class Program
{
static int Main()
{
var t = new { Test = 1 };
return 0;
}
}";
// Dev11: omits methods that are not defined on Object (see also Dev10 bug 487707)
// Roslyn: we require Equals, ToString, GetHashCode, Format to be defined
var comp = CreateEmptyCompilation(new[] { Parse(source), s_equalityComparerSourceTree }, new[] { MinCorlibRef });
var result = comp.Emit(new MemoryStream());
result.Diagnostics.Verify(
// error CS0656: Missing compiler required member 'System.Object.Equals'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "Equals"),
// error CS0656: Missing compiler required member 'System.Object.ToString'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "ToString"),
// error CS0656: Missing compiler required member 'System.Object.GetHashCode'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "GetHashCode"),
// error CS0656: Missing compiler required member 'System.String.Format'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.String", "Format"));
}
[Fact, WorkItem(530365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530365")]
public void NoDebuggerBrowsableStateType()
{
var stateSource = @"
namespace System.Diagnostics
{
public enum DebuggerBrowsableState
{
Collapsed = 2,
Never = 0,
RootHidden = 3
}
}
";
var stateLib = CreateEmptyCompilation(stateSource, new[] { MinCorlibRef });
var attributeSource = @"
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=false)]
public sealed class DebuggerBrowsableAttribute : Attribute
{
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
}
}
}
";
var attributeLib = CreateEmptyCompilation(attributeSource, new[] { MinCorlibRef, stateLib.ToMetadataReference() });
var source = @"
class Program
{
static int Main()
{
var t = new { Test = 1 };
return 0;
}
}";
var comp = CreateEmptyCompilation(new[] { Parse(source), s_equalityComparerSourceTree }, new[] { MinCorlibRef, attributeLib.ToMetadataReference() });
var result = comp.Emit(new MemoryStream());
result.Diagnostics.Verify(
// error CS0656: Missing compiler required member 'System.Object.Equals'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "Equals"),
// error CS0656: Missing compiler required member 'System.Object.ToString'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "ToString"),
// error CS0656: Missing compiler required member 'System.Object.GetHashCode'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "GetHashCode"),
// error CS0656: Missing compiler required member 'System.String.Format'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.String", "Format"));
}
[Fact]
public void ConditionalAccessErrors()
{
var source = @"
class C
{
int M() { return 0; }
void Test()
{
C local = null;
C[] array = null;
var x1 = new { local?.M() };
var x2 = new { array?[0] };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,24): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// var x1 = new { local?.M() };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "local?.M()").WithLocation(12, 24),
// (13,24): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// var x2 = new { array?[0] };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "array?[0]").WithLocation(13, 24));
}
[ClrOnlyFact]
[WorkItem(991505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991505")]
[WorkItem(199, "CodePlex")]
public void Bug991505()
{
var source = @"
class C
{
C P { get { return null; } }
int L { get { return 0; } }
int M { get { return 0; } }
int N { get { return 0; } }
void Test()
{
C local = null;
C[] array = null;
var x1 = new { local };
var x2_1 = new { local.P };
var x2_2 = new { local?.P };
var x3_1 = new { local.L };
var x3_2 = new { local?.L };
var x4_1 = new { local.P.M };
var x4_2 = new { local?.P.M };
var x4_3 = new { local?.P?.M };
var x5_1 = new { array[0].N };
var x5_2 = new { array?[0].N };
}
}
";
CompileAndVerify(
source,
symbolValidator: module =>
TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new[] { "local" } },
new TypeDescr() { FieldNames = new[] { "P" } },
new TypeDescr() { FieldNames = new[] { "L" } },
new TypeDescr() { FieldNames = new[] { "M" } },
new TypeDescr() { FieldNames = new[] { "N" } }));
}
[ClrOnlyFact]
public void CallingCreateAnonymousTypeDoesNotChangeIL()
{
var source = @"
class C
{
public static void Main(string[] args)
{
var v = new { m1 = 1, m2 = true };
}
}";
var expectedIL = @"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int, bool>..ctor(int, bool)""
IL_0007: pop
IL_0008: ret
}";
CompileAndVerify(source).VerifyIL("C.Main", expectedIL);
var compilation = CreateCompilationWithMscorlib40(source);
compilation.CreateAnonymousTypeSymbol(
ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32).GetPublicSymbol(), compilation.GetSpecialType(SpecialType.System_Boolean).GetPublicSymbol()),
ImmutableArray.Create("m1", "m2"));
this.CompileAndVerify(compilation).VerifyIL("C.Main", expectedIL);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class AnonymousTypesSymbolTests : CompilingTestBase
{
[ClrOnlyFact]
public void AnonymousTypeSymbol_InQuery()
{
var source = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> r1 =
from int x in c1
let g = x * 10
let z = g + x*100
select x + z;
System.Console.WriteLine(r1);
}
}
";
var verifier = CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "x", "g" } },
new TypeDescr() { FieldNames = new string[] { "<>h__TransparentIdentifier0", "z" } }
)
);
TestAnonymousTypeFieldSymbols_InQuery(verifier.EmittedAssemblyData);
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_Mix()
{
var source = @"
using System;
namespace Test
{
class Program
{
static int Main()
{
int result = 0;
var a0 = new { b1 = true, b2 = false };
var a1 = new
{
b1 = 0123456789,
b2 = 1234567890U,
b3 = 2345678901u,
b4 = 3456789012L,
b5 = 4567890123l,
b6 = 5678901234UL,
b7 = 6789012345Ul,
b8 = 7890123456uL,
b9 = 8901234567ul,
b10 = 9012345678LU,
b11 = 9123456780Lu,
b12 = 1234567809lU,
b13 = 2345678091lu
};
return result;
}
}
}
";
CompileAndVerify(source);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
return (Func<object>) (() => new { x2 });
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty2()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
Func<object> x3 = () => new { x2 };
return x3;
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty3()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>());
Console.WriteLine(Goo<string>());
Console.WriteLine(Goo<int?>());
}
static object Goo<T>()
{
T x2 = default(T);
return new { x2 };
}
}";
CompileAndVerify(
source,
expectedOutput:
@"{ x2 = 0 }
{ x2 = }
{ x2 = }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_NonEmpty4()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
foreach(var x in Goo<int>())
{
Console.Write(x);
}
}
static IEnumerable<object> Goo<T>()
{
T x2 = default(T);
yield return new { x2 }.ToString();
yield return new { YYY = default(T), z = new { field = x2 } };
}
}";
CompileAndVerify(
source,
expectedOutput: "{ x2 = 0 }{ YYY = 0, z = { field = 0 } }"
);
}
[ClrOnlyFact]
public void AnonymousTypeInConstructedMethod_Empty()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Goo<int>()());
}
static Func<object> Goo<T>()
{
T x2 = default(T);
return (Func<object>) (() => new { });
}
}";
CompileAndVerify(
source,
expectedOutput: "{ }"
);
}
#region AnonymousTypeSymbol_InQuery :: Checking fields via reflection
private void TestAnonymousTypeFieldSymbols_InQuery(ImmutableArray<byte> image)
{
Assembly refAsm = Assembly.Load(image.ToArray());
Type type = refAsm.GetType("<>f__AnonymousType0`2");
Assert.NotNull(type);
Assert.Equal(2, type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Count());
CheckField(type.GetField("<x>i__Field", BindingFlags.NonPublic | BindingFlags.Instance), type.GetGenericArguments()[0]);
CheckField(type.GetField("<g>i__Field", BindingFlags.NonPublic | BindingFlags.Instance), type.GetGenericArguments()[1]);
}
private void CheckField(FieldInfo field, Type fieldType)
{
Assert.NotNull(field);
Assert.NotNull(fieldType);
Assert.Equal(fieldType, field.FieldType);
Assert.Equal(FieldAttributes.Private | FieldAttributes.InitOnly, field.Attributes);
var attrs = field.CustomAttributes.ToList();
Assert.Equal(1, attrs.Count);
Assert.Equal(typeof(DebuggerBrowsableAttribute), attrs[0].AttributeType);
var args = attrs[0].ConstructorArguments.ToArray();
Assert.Equal(1, args.Length);
Assert.Equal(typeof(DebuggerBrowsableState), args[0].ArgumentType);
Assert.Equal(DebuggerBrowsableState.Never, (DebuggerBrowsableState)args[0].Value);
}
#endregion
[ClrOnlyFact]
public void AnonymousTypeSymbol_Simple()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { a = 1, b = 2 };
object at2 = new { (new string[2]).Length, at1, C = new Object() };
object at3 = new { a = '1', b = at1 };
PrintFields(at1.GetType());
PrintFields(at2.GetType());
PrintFields(at3.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "a", "b" } },
new TypeDescr() { FieldNames = new string[] { "Length", "at1", "C" } }
),
expectedOutput: @"
<>f__AnonymousType0`2:
Private, InitOnly Int32 <a>i__Field
Private, InitOnly Int32 <b>i__Field
<>f__AnonymousType1`3:
Private, InitOnly Int32 <Length>i__Field
Private, InitOnly <>f__AnonymousType0`2 <at1>i__Field
Private, InitOnly Object <C>i__Field
<>f__AnonymousType0`2:
Private, InitOnly Char <a>i__Field
Private, InitOnly <>f__AnonymousType0`2 <b>i__Field
"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>..ctor(<Length>j__TPar, <at1>j__TPar, <C>j__TPar)",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_000d: ldarg.0
IL_000e: ldarg.2
IL_000f: stfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0014: ldarg.0
IL_0015: ldarg.3
IL_0016: stfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_001b: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.Length.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.at1.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.C.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.Equals",
@"{
// Code size 89 (0x59)
.maxstack 3
.locals init (<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar> V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0057
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0055
IL_000e: call ""System.Collections.Generic.EqualityComparer<<Length>j__TPar> System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Default.get""
IL_0013: ldarg.0
IL_0014: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0019: ldloc.0
IL_001a: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_001f: callvirt ""bool System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Equals(<Length>j__TPar, <Length>j__TPar)""
IL_0024: brfalse.s IL_0055
IL_0026: call ""System.Collections.Generic.EqualityComparer<<at1>j__TPar> System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Default.get""
IL_002b: ldarg.0
IL_002c: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0031: ldloc.0
IL_0032: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_0037: callvirt ""bool System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Equals(<at1>j__TPar, <at1>j__TPar)""
IL_003c: brfalse.s IL_0055
IL_003e: call ""System.Collections.Generic.EqualityComparer<<C>j__TPar> System.Collections.Generic.EqualityComparer<<C>j__TPar>.Default.get""
IL_0043: ldarg.0
IL_0044: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0049: ldloc.0
IL_004a: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_004f: callvirt ""bool System.Collections.Generic.EqualityComparer<<C>j__TPar>.Equals(<C>j__TPar, <C>j__TPar)""
IL_0054: ret
IL_0055: ldc.i4.0
IL_0056: ret
IL_0057: ldc.i4.1
IL_0058: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.GetHashCode",
@"{
// Code size 75 (0x4b)
.maxstack 3
IL_0000: ldc.i4 " + GetHashCodeInitialValue("<Length>i__Field", "<at1>i__Field", "<C>i__Field") + @"
IL_0005: ldc.i4 0xa5555529
IL_000a: mul
IL_000b: call ""System.Collections.Generic.EqualityComparer<<Length>j__TPar> System.Collections.Generic.EqualityComparer<<Length>j__TPar>.Default.get""
IL_0010: ldarg.0
IL_0011: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0016: callvirt ""int System.Collections.Generic.EqualityComparer<<Length>j__TPar>.GetHashCode(<Length>j__TPar)""
IL_001b: add
IL_001c: ldc.i4 0xa5555529
IL_0021: mul
IL_0022: call ""System.Collections.Generic.EqualityComparer<<at1>j__TPar> System.Collections.Generic.EqualityComparer<<at1>j__TPar>.Default.get""
IL_0027: ldarg.0
IL_0028: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_002d: callvirt ""int System.Collections.Generic.EqualityComparer<<at1>j__TPar>.GetHashCode(<at1>j__TPar)""
IL_0032: add
IL_0033: ldc.i4 0xa5555529
IL_0038: mul
IL_0039: call ""System.Collections.Generic.EqualityComparer<<C>j__TPar> System.Collections.Generic.EqualityComparer<<C>j__TPar>.Default.get""
IL_003e: ldarg.0
IL_003f: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0044: callvirt ""int System.Collections.Generic.EqualityComparer<<C>j__TPar>.GetHashCode(<C>j__TPar)""
IL_0049: add
IL_004a: ret
}"
).VerifyIL(
"<>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.ToString",
@"{
// Code size 138 (0x8a)
.maxstack 7
.locals init (<Length>j__TPar V_0,
<at1>j__TPar V_1,
<C>j__TPar V_2)
IL_0000: ldnull
IL_0001: ldstr ""{{ Length = {0}, at1 = {1}, C = {2} }}""
IL_0006: ldc.i4.3
IL_0007: newarr ""object""
IL_000c: dup
IL_000d: ldc.i4.0
IL_000e: ldarg.0
IL_000f: ldfld ""<Length>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<Length>i__Field""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: dup
IL_0018: ldobj ""<Length>j__TPar""
IL_001d: box ""<Length>j__TPar""
IL_0022: brtrue.s IL_0028
IL_0024: pop
IL_0025: ldnull
IL_0026: br.s IL_0033
IL_0028: constrained. ""<Length>j__TPar""
IL_002e: callvirt ""string object.ToString()""
IL_0033: stelem.ref
IL_0034: dup
IL_0035: ldc.i4.1
IL_0036: ldarg.0
IL_0037: ldfld ""<at1>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<at1>i__Field""
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: dup
IL_0040: ldobj ""<at1>j__TPar""
IL_0045: box ""<at1>j__TPar""
IL_004a: brtrue.s IL_0050
IL_004c: pop
IL_004d: ldnull
IL_004e: br.s IL_005b
IL_0050: constrained. ""<at1>j__TPar""
IL_0056: callvirt ""string object.ToString()""
IL_005b: stelem.ref
IL_005c: dup
IL_005d: ldc.i4.2
IL_005e: ldarg.0
IL_005f: ldfld ""<C>j__TPar <>f__AnonymousType1<<Length>j__TPar, <at1>j__TPar, <C>j__TPar>.<C>i__Field""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: dup
IL_0068: ldobj ""<C>j__TPar""
IL_006d: box ""<C>j__TPar""
IL_0072: brtrue.s IL_0078
IL_0074: pop
IL_0075: ldnull
IL_0076: br.s IL_0083
IL_0078: constrained. ""<C>j__TPar""
IL_007e: callvirt ""string object.ToString()""
IL_0083: stelem.ref
IL_0084: call ""string string.Format(System.IFormatProvider, string, params object[])""
IL_0089: ret
}"
);
}
[Fact]
public void AnonymousTypeSymbol_Simple_Threadsafety()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { a = 1, b = 2 };
var at2 = new { a = 1, b = 2, c = 3};
var at3 = new { a = 1, b = 2, c = 3, d = 4};
var at4 = new { a = 1, b = 2, c = 3, d = 4, e = 5};
var at5 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at6 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at7 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at8 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at9 = new { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at11 = new { aa = 1, b = 2 };
var at12 = new { aa = 1, b = 2, c = 3};
var at13 = new { aa = 1, b = 2, c = 3, d = 4};
var at14 = new { aa = 1, b = 2, c = 3, d = 4, e = 5};
var at15 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at16 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at17 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at18 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at19 = new { aa = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at21 = new { ba = 1, b = 2 };
var at22 = new { ba = 1, b = 2, c = 3};
var at23 = new { ba = 1, b = 2, c = 3, d = 4};
var at24 = new { ba = 1, b = 2, c = 3, d = 4, e = 5};
var at25 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at26 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at27 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at28 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at29 = new { ba = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at31 = new { ca = 1, b = 2 };
var at32 = new { ca = 1, b = 2, c = 3};
var at33 = new { ca = 1, b = 2, c = 3, d = 4};
var at34 = new { ca = 1, b = 2, c = 3, d = 4, e = 5};
var at35 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at36 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at37 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at38 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at39 = new { ca = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
var at41 = new { da = 1, b = 2 };
var at42 = new { da = 1, b = 2, c = 3};
var at43 = new { da = 1, b = 2, c = 3, d = 4};
var at44 = new { da = 1, b = 2, c = 3, d = 4, e = 5};
var at45 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6};
var at46 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7};
var at47 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8};
var at48 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9};
var at49 = new { da = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, j = 9, k = 10};
PrintFields(at1.GetType());
PrintFields(at2.GetType());
PrintFields(at3.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
for (int i = 0; i < 100; i++)
{
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
var tasks = new Task[10];
for (int j = 0; j < tasks.Length; j++)
{
var metadataOnly = j % 2 == 0;
tasks[j] = Task.Run(() =>
{
var stream = new MemoryStream();
var result = compilation.Emit(stream, options: new EmitOptions(metadataOnly: metadataOnly));
result.Diagnostics.Verify();
});
}
// this should not fail. if you ever see a NRE or some kind of crash here enter a bug.
// it may be reproducing just once in a while, in Release only...
// it is still a bug.
Task.WaitAll(tasks);
}
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_Empty()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { };
var at2 = new { };
at2 = at1;
string x = at1.ToString() + at2.ToString();
PrintFields(at1.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { } }
),
expectedOutput: @"
<>f__AnonymousType0:
"
).VerifyIL(
"<>f__AnonymousType0..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0.Equals",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init (<>f__AnonymousType0 V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType0""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0010
IL_000b: ldloc.0
IL_000c: ldnull
IL_000d: cgt.un
IL_000f: ret
IL_0010: ldc.i4.1
IL_0011: ret
}"
).VerifyIL(
"<>f__AnonymousType0.GetHashCode",
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}"
).VerifyIL(
"<>f__AnonymousType0.ToString",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""{ }""
IL_0005: ret
}"
);
}
[WorkItem(543022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543022")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_StandardNames()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { GetHashCode = new { } };
Console.Write(at1.GetType());
Console.Write(""-"");
Console.Write(at1.GetHashCode.GetType());
}
}
";
CompileAndVerify(
source,
expectedOutput: "<>f__AnonymousType0`1[<>f__AnonymousType1]-<>f__AnonymousType1");
}
[WorkItem(543022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543022")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_StandardNames2()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { ToString = ""Field"" };
Console.Write(at1.ToString());
Console.Write(""-"");
Console.Write(at1.ToString);
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ ToString = Field }-Field");
}
[Fact]
public void AnonymousTypeSymbol_StandardNames3()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var at1 = new { ToString = 1, Equals = new Object(), GetHashCode = ""GetHashCode"" };
PrintFields(at1.GetType());
}
static void PrintFields(Type type)
{
Console.WriteLine(type.Name + "": "");
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic))
{
Console.Write("" "");
Console.Write(field.Attributes);
Console.Write("" "");
Console.Write(field.FieldType.Name);
Console.Write("" "");
Console.Write(field.Name);
Console.WriteLine();
}
}
}
";
CompileAndVerify(
source,
symbolValidator: module => TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new string[] { "ToString", "Equals", "GetHashCode" } }
),
expectedOutput: @"
<>f__AnonymousType0`3:
Private, InitOnly Int32 <ToString>i__Field
Private, InitOnly Object <Equals>i__Field
Private, InitOnly String <GetHashCode>i__Field
"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>..ctor",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_000d: ldarg.0
IL_000e: ldarg.2
IL_000f: stfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0014: ldarg.0
IL_0015: ldarg.3
IL_0016: stfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_001b: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.Equals",
@"{
// Code size 89 (0x59)
.maxstack 3
.locals init (<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar> V_0)
IL_0000: ldarg.1
IL_0001: isinst ""<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldloc.0
IL_0009: beq.s IL_0057
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0055
IL_000e: call ""System.Collections.Generic.EqualityComparer<<ToString>j__TPar> System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Default.get""
IL_0013: ldarg.0
IL_0014: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0019: ldloc.0
IL_001a: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_001f: callvirt ""bool System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Equals(<ToString>j__TPar, <ToString>j__TPar)""
IL_0024: brfalse.s IL_0055
IL_0026: call ""System.Collections.Generic.EqualityComparer<<Equals>j__TPar> System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Default.get""
IL_002b: ldarg.0
IL_002c: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0031: ldloc.0
IL_0032: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0037: callvirt ""bool System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Equals(<Equals>j__TPar, <Equals>j__TPar)""
IL_003c: brfalse.s IL_0055
IL_003e: call ""System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar> System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Default.get""
IL_0043: ldarg.0
IL_0044: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0049: ldloc.0
IL_004a: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_004f: callvirt ""bool System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Equals(<GetHashCode>j__TPar, <GetHashCode>j__TPar)""
IL_0054: ret
IL_0055: ldc.i4.0
IL_0056: ret
IL_0057: ldc.i4.1
IL_0058: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.GetHashCode",
@"{
// Code size 75 (0x4b)
.maxstack 3
IL_0000: ldc.i4 0x3711624
IL_0005: ldc.i4 0xa5555529
IL_000a: mul
IL_000b: call ""System.Collections.Generic.EqualityComparer<<ToString>j__TPar> System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.Default.get""
IL_0010: ldarg.0
IL_0011: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0016: callvirt ""int System.Collections.Generic.EqualityComparer<<ToString>j__TPar>.GetHashCode(<ToString>j__TPar)""
IL_001b: add
IL_001c: ldc.i4 0xa5555529
IL_0021: mul
IL_0022: call ""System.Collections.Generic.EqualityComparer<<Equals>j__TPar> System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.Default.get""
IL_0027: ldarg.0
IL_0028: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_002d: callvirt ""int System.Collections.Generic.EqualityComparer<<Equals>j__TPar>.GetHashCode(<Equals>j__TPar)""
IL_0032: add
IL_0033: ldc.i4 0xa5555529
IL_0038: mul
IL_0039: call ""System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar> System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.Default.get""
IL_003e: ldarg.0
IL_003f: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0044: callvirt ""int System.Collections.Generic.EqualityComparer<<GetHashCode>j__TPar>.GetHashCode(<GetHashCode>j__TPar)""
IL_0049: add
IL_004a: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.ToString",
@"{
// Code size 138 (0x8a)
.maxstack 7
.locals init (<ToString>j__TPar V_0,
<Equals>j__TPar V_1,
<GetHashCode>j__TPar V_2)
IL_0000: ldnull
IL_0001: ldstr ""{{ ToString = {0}, Equals = {1}, GetHashCode = {2} }}""
IL_0006: ldc.i4.3
IL_0007: newarr ""object""
IL_000c: dup
IL_000d: ldc.i4.0
IL_000e: ldarg.0
IL_000f: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: dup
IL_0018: ldobj ""<ToString>j__TPar""
IL_001d: box ""<ToString>j__TPar""
IL_0022: brtrue.s IL_0028
IL_0024: pop
IL_0025: ldnull
IL_0026: br.s IL_0033
IL_0028: constrained. ""<ToString>j__TPar""
IL_002e: callvirt ""string object.ToString()""
IL_0033: stelem.ref
IL_0034: dup
IL_0035: ldc.i4.1
IL_0036: ldarg.0
IL_0037: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_003c: stloc.1
IL_003d: ldloca.s V_1
IL_003f: dup
IL_0040: ldobj ""<Equals>j__TPar""
IL_0045: box ""<Equals>j__TPar""
IL_004a: brtrue.s IL_0050
IL_004c: pop
IL_004d: ldnull
IL_004e: br.s IL_005b
IL_0050: constrained. ""<Equals>j__TPar""
IL_0056: callvirt ""string object.ToString()""
IL_005b: stelem.ref
IL_005c: dup
IL_005d: ldc.i4.2
IL_005e: ldarg.0
IL_005f: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: dup
IL_0068: ldobj ""<GetHashCode>j__TPar""
IL_006d: box ""<GetHashCode>j__TPar""
IL_0072: brtrue.s IL_0078
IL_0074: pop
IL_0075: ldnull
IL_0076: br.s IL_0083
IL_0078: constrained. ""<GetHashCode>j__TPar""
IL_007e: callvirt ""string object.ToString()""
IL_0083: stelem.ref
IL_0084: call ""string string.Format(System.IFormatProvider, string, params object[])""
IL_0089: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.ToString.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<ToString>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<ToString>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.Equals.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<Equals>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<Equals>i__Field""
IL_0006: ret
}"
).VerifyIL(
"<>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.GetHashCode.get",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<GetHashCode>j__TPar <>f__AnonymousType0<<ToString>j__TPar, <Equals>j__TPar, <GetHashCode>j__TPar>.<GetHashCode>i__Field""
IL_0006: ret
}"
);
}
#region "Utility methods"
/// <summary>
/// This method duplicates the generation logic for initial value used
/// in anonymous type's GetHashCode function
/// </summary>
public static string GetHashCodeInitialValue(params string[] names)
{
const int HASH_FACTOR = -1521134295; // (int)0xa5555529
int init = 0;
foreach (var name in names)
{
init = unchecked(init * HASH_FACTOR + Hash.GetFNVHashCode(name));
}
return "0x" + init.ToString("X").ToLower();
}
private struct TypeDescr
{
public string[] FieldNames;
}
private void TestAnonymousTypeSymbols(ModuleSymbol module, params TypeDescr[] typeDescrs)
{
int cnt = typeDescrs.Length;
Assert.Equal(0, module.GlobalNamespace.GetMembers("<>f__AnonymousType" + cnt.ToString()).Length);
// test template classes
for (int i = 0; i < cnt; i++)
{
TestAnonymousType(module.GlobalNamespace.GetMember<NamedTypeSymbol>("<>f__AnonymousType" + i.ToString()), i, typeDescrs[i]);
}
}
private void TestAnonymousType(NamedTypeSymbol type, int typeIndex, TypeDescr typeDescr)
{
Assert.NotEqual(default, typeDescr);
Assert.NotNull(typeDescr.FieldNames);
// prepare
int fieldsCount = typeDescr.FieldNames.Length;
string[] genericParameters = new string[fieldsCount];
string genericParametersList = null;
for (int i = 0; i < fieldsCount; i++)
{
genericParameters[i] = String.Format("<{0}>j__TPar", typeDescr.FieldNames[i]);
genericParametersList = genericParametersList == null
? genericParameters[i]
: genericParametersList + ", " + genericParameters[i];
}
string genericParametersSuffix = fieldsCount == 0 ? "" : "<" + genericParametersList + ">";
string typeViewName = String.Format("<>f__AnonymousType{0}{1}", typeIndex.ToString(), genericParametersSuffix);
// test
Assert.Equal(typeViewName, type.ToDisplayString());
Assert.Equal("object", type.BaseType().ToDisplayString());
Assert.True(fieldsCount == 0 ? !type.IsGenericType : type.IsGenericType);
Assert.Equal(fieldsCount, type.Arity);
Assert.Equal(Accessibility.Internal, type.DeclaredAccessibility);
Assert.True(type.IsSealed);
Assert.False(type.IsStatic);
Assert.Equal(0, type.Interfaces().Length);
// test non-existing members
Assert.Equal(0, type.GetMembers("doesnotexist").Length);
TestAttributeOnSymbol(
type,
new AttributeInfo
{
CtorName = "System.Runtime.CompilerServices.CompilerGeneratedAttribute.CompilerGeneratedAttribute()",
ConstructorArguments = new string[] { }
}
);
// test properties
for (int i = 0; i < fieldsCount; i++)
{
var typeParameter = type.TypeParameters[i];
Assert.Equal(genericParameters[i], typeParameter.ToDisplayString());
TestAnonymousTypeProperty(type, typeViewName, typeDescr.FieldNames[i], typeParameter);
}
// methods
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, ".ctor"),
String.Format("{0}.<>f__AnonymousType{1}({2})", typeViewName, typeIndex.ToString(), genericParametersList),
"void",
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "Equals"),
String.Format("{0}.Equals(object)", typeViewName),
"bool",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "GetHashCode"),
String.Format("{0}.GetHashCode()", typeViewName),
"int",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
CheckMethodSymbol(
this.GetMemberByName<MethodSymbol>(type, "ToString"),
String.Format("{0}.ToString()", typeViewName),
"string",
isVirtualAndOverride: true,
attr: new AttributeInfo() { CtorName = "System.Diagnostics.DebuggerHiddenAttribute.DebuggerHiddenAttribute()", ConstructorArguments = new string[] { } }
);
}
private T GetMemberByName<T>(NamedTypeSymbol type, string name) where T : Symbol
{
foreach (var symbol in type.GetMembers(name))
{
if (symbol is T)
{
return (T)symbol;
}
}
return null;
}
private void TestAnonymousTypeProperty(NamedTypeSymbol type, string typeViewName, string name, TypeSymbol propType)
{
PropertySymbol property = this.GetMemberByName<PropertySymbol>(type, name);
Assert.NotNull(property);
Assert.Equal(propType, property.Type);
Assert.Equal(Accessibility.Public, property.DeclaredAccessibility);
Assert.False(property.IsAbstract);
Assert.False(property.IsIndexer);
Assert.False(property.IsOverride);
Assert.True(property.IsReadOnly);
Assert.False(property.IsStatic);
Assert.False(property.IsSealed);
Assert.False(property.IsVirtual);
Assert.False(property.IsWriteOnly);
var getter = property.GetMethod;
Assert.NotNull(getter);
Assert.Equal("get_" + name, getter.Name);
CheckMethodSymbol(
getter,
typeViewName + "." + name + ".get",
propType.ToDisplayString()
);
}
private void CheckMethodSymbol(
MethodSymbol method,
string signature,
string retType,
bool isVirtualAndOverride = false,
AttributeInfo attr = null
)
{
Assert.NotNull(method);
Assert.Equal(signature, method.ToDisplayString());
Assert.Equal(Accessibility.Public, method.DeclaredAccessibility);
Assert.False(method.IsAbstract);
Assert.Equal(isVirtualAndOverride, method.IsOverride);
Assert.False(method.IsStatic);
Assert.False(method.IsSealed);
Assert.False(method.IsVararg);
Assert.False(method.IsVirtual);
Assert.Equal(isVirtualAndOverride, method.IsMetadataVirtual());
Assert.Equal(retType, method.ReturnTypeWithAnnotations.ToDisplayString());
TestAttributeOnSymbol(method, attr == null ? new AttributeInfo[] { } : new AttributeInfo[] { attr });
}
private class AttributeInfo
{
public string CtorName;
public string[] ConstructorArguments;
}
private void TestAttributeOnSymbol(Symbol symbol, params AttributeInfo[] attributes)
{
var actual = symbol.GetAttributes();
Assert.Equal(attributes.Length, actual.Length);
for (int index = 0; index < attributes.Length; index++)
{
var attr = attributes[index];
Assert.Equal(attr.CtorName, actual[index].AttributeConstructor.ToDisplayString());
Assert.Equal(attr.ConstructorArguments.Length, actual[index].CommonConstructorArguments.Length);
for (int argIndex = 0; argIndex < attr.ConstructorArguments.Length; argIndex++)
{
Assert.Equal(
attr.ConstructorArguments[argIndex],
actual[index].CommonConstructorArguments[argIndex].Value.ToString()
);
}
}
}
#endregion
[ClrOnlyFact]
public void AnonymousType_BaseAccess()
{
var source = @"
using System;
class Base
{
protected int field = 123;
}
class Derived: Base
{
public static void Main(string[] args)
{
(new Derived()).Test();
}
public void Test()
{
var a = new { base.field };
Console.WriteLine(a.ToString());
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ field = 123 }");
}
[ClrOnlyFact]
public void AnonymousType_PropertyAccess()
{
var source = @"
using System;
class Class1
{
public static void Main(string[] args)
{
var a = new { (new Class1()).PropertyA };
Console.WriteLine(a.ToString());
}
public string PropertyA
{
get { return ""pa-value""; }
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ PropertyA = pa-value }");
}
[ClrOnlyFact]
public void AnonymousType_Simple()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
int a = (new {a = 1, b=""text"", }).a;
string b = (new {a = 1, b=""text""}).b;
Console.WriteLine(string.Format(""a={0}; b={1}"", a, b));
}
}
";
CompileAndVerify(
source,
expectedOutput: "a=1; b=text");
}
[ClrOnlyFact]
public void AnonymousType_CustModifiersOnPropertyFields()
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
var intArrMod = Modifiers.F9();
var at1 = new { f = intArrMod };
var at2 = new { f = new int[] {} };
at1 = at2;
at2 = at1;
}
}
";
CompileAndVerify(
source,
references: new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll });
}
[ClrOnlyFact]
public void AnonymousType_ToString()
{
// test AnonymousType.ToString()
using (new EnsureInvariantCulture())
{
var source = @"
using System;
class Query
{
public static void Main(string[] args)
{
Console.WriteLine((new { a = 1, b=""text"", c=123.456}).ToString());
}
}
";
CompileAndVerify(
source,
expectedOutput: "{ a = 1, b = text, c = 123.456 }");
}
}
[ClrOnlyFact]
public void AnonymousType_Equals()
{
var source = @"
using System;
using System.Collections.Generic;
struct S: IEquatable<S>
{
public int X;
public int Y;
public S(int x, int y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return string.Format(""({0}, {1})"", this.X, this.Y);
}
public bool Equals(S other)
{
bool equals = this.X == other.X && this.Y == other.Y;
this.X = other.X = -1;
this.Y = other.Y = -1;
return equals;
}
}
class Query
{
public static void Main(string[] args)
{
Compare(new { a = new S(1, 2), b = new S(1, 2) }, new { a = new S(1, 2), b = new S(1, 2) });
Compare(new { a = new S(1, 2), b = new S(1, 2) }, new { b = new S(1, 2), a = new S(1, 2) });
object a = new { a = new S(1, 2) };
Compare(a, new { a = new S(1, 2) });
Compare(a, new { a = new S(-1, -1) });
Compare(new { a = new S(1, 2) }, a);
Compare(new { a = new S(-1, -1) }, a);
}
public static void Compare(object a, object b)
{
Console.WriteLine(string.Format(""{0}.Equals({1}) = {2}"", a.ToString(), b.ToString(), a.Equals(b).ToString()));
}
}";
CompileAndVerify(
source,
expectedOutput: @"
{ a = (1, 2), b = (1, 2) }.Equals({ a = (1, 2), b = (1, 2) }) = True
{ a = (1, 2), b = (1, 2) }.Equals({ b = (1, 2), a = (1, 2) }) = False
{ a = (1, 2) }.Equals({ a = (1, 2) }) = True
{ a = (1, 2) }.Equals({ a = (-1, -1) }) = False
{ a = (1, 2) }.Equals({ a = (1, 2) }) = True
{ a = (-1, -1) }.Equals({ a = (1, 2) }) = False
");
}
[ClrOnlyFact]
public void AnonymousType_GetHashCode()
{
var source = @"
using System;
struct S
{
public int X;
public int Y;
public S(int x, int y)
{
this.X = x;
this.Y = y;
}
public override bool Equals(object obj)
{
throw new Exception();
}
public override int GetHashCode()
{
return this.X + this.Y;
}
public override string ToString()
{
return string.Format(""({0}, {1})"", this.X, this.Y);
}
}
class Query
{
public static void Main(string[] args)
{
Print(new { }, new S(0, 0));
Print(new { a = new S(2, 2), b = new S(1, 2) }, new { a = new S(4, 0), b = new S(2, 1) });
Print(new { a = new S(4, 0), b = new S(2, 1) }, new { b = new S(4, 0), a = new S(2, 1) });
}
public static void Print(object a, object b)
{
Console.WriteLine(string.Format(""{0}.GetHashCode() == {1}.GetHashCode() = {2}"", a.ToString(), b.ToString(), a.GetHashCode() == b.GetHashCode()));
}
}
";
CompileAndVerify(
source,
expectedOutput: @"
{ }.GetHashCode() == (0, 0).GetHashCode() = True
{ a = (2, 2), b = (1, 2) }.GetHashCode() == { a = (4, 0), b = (2, 1) }.GetHashCode() = True
{ a = (4, 0), b = (2, 1) }.GetHashCode() == { b = (4, 0), a = (2, 1) }.GetHashCode() = False
");
}
[ClrOnlyFact]
public void AnonymousType_MultiplyEmitDoesNotChangeTheOrdering()
{
// this test checks whether or not anonymous types which came from speculative
// semantic API have any effect on the anonymous types emitted and
// whether or not the order is still the same across several emits
var source1 = @"
using System;
class Class2
{
public static void Main2()
{
var d = new { args = 0 };
var b = new { a = """", b = 1 };
}
}
";
var source2 = @"
using System;
class Class1
{
public static void Main(string[] args)
{
var a = new { };
var b = new { a = """", b = 1 };
var c = new { b = 1, a = .2 };
var d = new { args };
}
}
";
var source3 = @"
using System;
class Class3
{
public static void Main2()
{
var c = new { b = 1, a = .2 };
var a = new { };
}
}
";
var compilation = CreateCompilationWithMscorlib40(new string[] { source1, source2, source3 }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), parseOptions: TestOptions.Regular);
for (int i = 0; i < 10; i++)
{
this.CompileAndVerify(
compilation,
symbolValidator: module =>
{
var types = module.GlobalNamespace.GetTypeMembers()
.Where(t => t.Name.StartsWith("<>", StringComparison.Ordinal))
.Select(t => t.ToDisplayString())
.OrderBy(t => t)
.ToArray();
Assert.Equal(4, types.Length);
Assert.Equal("<>f__AnonymousType0<<args>j__TPar>", types[0]);
Assert.Equal("<>f__AnonymousType1<<a>j__TPar, <b>j__TPar>", types[1]);
Assert.Equal("<>f__AnonymousType2", types[2]);
Assert.Equal("<>f__AnonymousType3<<b>j__TPar, <a>j__TPar>", types[3]);
},
verify: Verification.Passes
);
// do some speculative semantic query
var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]);
var position = source1.IndexOf("var d", StringComparison.Ordinal) - 1;
var expr1 = SyntaxFactory.ParseExpression("new { x = 1, y" + i.ToString() + " = \"---\" }");
var info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(info1.Type);
}
}
[WorkItem(543134, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543134")]
[ClrOnlyFact]
public void AnonymousTypeSymbol_Simple_1()
{
var source = @"
class Test
{
public static void Main()
{
var a = new { };
var b = new { p1 = 10 };
}
}
";
CompileAndVerify(source);
}
[ClrOnlyFact]
public void AnonymousTypeSymbol_NamesConflictInsideLambda()
{
var source = @"
using System;
class Test
{
public static void Main()
{
M(123);
}
public static void M<T>(T p)
{
Action a = () => { Console.Write(new { x = 1221, get_x = p }.x.ToString()); };
a();
}
}
";
CompileAndVerify(source, expectedOutput: "1221");
}
[WorkItem(543693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543693")]
[ClrOnlyFact]
public void Bug11593a()
{
var source = @"
delegate T Func<A0, T>(A0 a0);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public Y<T> Select<T>(Func<U, T> selector)
{
return new Y<T>(selector(u));
}
}
class P
{
static void Main()
{
var src = new Y<int>(2);
var q = from x in src
let y = x + 3
select new { X = x, Y = y };
if ((q.u.X != 2 || q.u.Y != 5))
{
}
System.Console.WriteLine(""Success"");
}
}
";
CompileAndVerify(source, expectedOutput: "Success");
}
[WorkItem(543693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543693")]
[ClrOnlyFact]
public void Bug11593b()
{
var source = @"
delegate T Func<A0, T>(A0 a0);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public Y<T> Select<T>(Func<U, T> selector)
{
return new Y<T>(selector(u));
}
}
class P
{
static void Main()
{
var xxx = new { X = 1, Y = 2 };
var src = new Y<int>(2);
var q = from x in src
let y = x + 3
select new { X = x, Y = y };
if ((q.u.X != 2 || q.u.Y != 5))
{
}
System.Console.WriteLine(""Success"");
}
}
";
CompileAndVerify(source, expectedOutput: "Success");
}
[WorkItem(543177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543177")]
[ClrOnlyFact]
public void AnonymousTypePropertyValueWithWarning()
{
var source = @"
using System;
class Program
{
static void Main()
{
var a1 = new
{
p1 = 0123456789L,
p2 = 0123456789l, // Warning CS0078
};
Console.Write(a1.p1 == a1.p2);
}
}
";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact(), WorkItem(544323, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544323")]
public void AnonymousTypeAndMemberSymbolsLocations()
{
var source = @"
using System;
class Program
{
static void Main()
{
var an = new { id = 1, name = ""QC"" };
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single();
var sym = model.GetSymbolInfo(expr);
Assert.NotNull(sym.Symbol);
Assert.True(sym.Symbol.GetSymbol().IsFromCompilation(comp), "IsFromCompilation");
Assert.False(sym.Symbol.Locations.IsEmpty, "Symbol Location");
Assert.True(sym.Symbol.Locations[0].IsInSource);
var info = model.GetTypeInfo(expr);
Assert.NotNull(info.Type);
var mems = info.Type.GetMembers();
foreach (var m in mems)
{
Assert.True(m.GetSymbol().IsFromCompilation(comp), "IsFromCompilation");
Assert.False(m.Locations.IsEmpty, String.Format("No Location: {0}", m));
Assert.True(m.Locations[0].IsInSource);
}
}
[Fact]
public void SameAnonymousTypeInTwoLocations()
{
// This code declares the same anonymous type twice. Make sure the locations
// reflect this.
var source = @"
using System;
class Program
{
static void Main()
{
var a1 = new { id = 1, name = ""QC"" };
var a2 = new { id = 1, name = ""QC"" };
var a3 = a1;
var a4 = a2;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var programType = (NamedTypeSymbol)(comp.GlobalNamespace.GetTypeMembers("Program").Single());
var mainMethod = (MethodSymbol)(programType.GetMembers("Main").Single());
var mainSyntax = mainMethod.DeclaringSyntaxReferences.Single().GetSyntax() as MethodDeclarationSyntax;
var mainBlock = mainSyntax.Body;
var statement1 = mainBlock.Statements[0] as LocalDeclarationStatementSyntax;
var statement2 = mainBlock.Statements[1] as LocalDeclarationStatementSyntax;
var statement3 = mainBlock.Statements[2] as LocalDeclarationStatementSyntax;
var statement4 = mainBlock.Statements[3] as LocalDeclarationStatementSyntax;
var localA3 = model.GetDeclaredSymbol(statement3.Declaration.Variables[0]) as ILocalSymbol;
var localA4 = model.GetDeclaredSymbol(statement4.Declaration.Variables[0]) as ILocalSymbol;
var typeA3 = localA3.Type;
var typeA4 = localA4.Type;
// A3 and A4 should have different type objects, that compare equal. They should have
// different locations.
Assert.Equal(typeA3, typeA4);
Assert.NotSame(typeA3, typeA4);
Assert.NotEqual(typeA3.Locations[0], typeA4.Locations[0]);
// The locations of a3's type should be the type declared in statement 1, the location
// of a4's type should be the type declared in statement 2.
Assert.True(statement1.Span.Contains(typeA3.Locations[0].SourceSpan));
Assert.True(statement2.Span.Contains(typeA4.Locations[0].SourceSpan));
}
private static readonly SyntaxTree s_equalityComparerSourceTree = Parse(@"
namespace System.Collections
{
public interface IEqualityComparer
{
bool Equals(object x, object y);
int GetHashCode(object obj);
}
}
namespace System.Collections.Generic
{
public interface IEqualityComparer<T>
{
bool Equals(T x, T y);
int GetHashCode(T obj);
}
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
protected EqualityComparer() { }
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
bool IEqualityComparer.Equals(object x, object y) { return true; }
int IEqualityComparer.GetHashCode(object obj) { return 0; }
// Properties
public static EqualityComparer<T> Default { get { return null; } }
}
}
");
/// <summary>
/// Bug#15914: Breaking Changes
/// </summary>
[Fact, WorkItem(530365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530365")]
public void NoStdLibNoEmitToStringForAnonymousType()
{
var source = @"
class Program
{
static int Main()
{
var t = new { Test = 1 };
return 0;
}
}";
// Dev11: omits methods that are not defined on Object (see also Dev10 bug 487707)
// Roslyn: we require Equals, ToString, GetHashCode, Format to be defined
var comp = CreateEmptyCompilation(new[] { Parse(source), s_equalityComparerSourceTree }, new[] { MinCorlibRef });
var result = comp.Emit(new MemoryStream());
result.Diagnostics.Verify(
// error CS0656: Missing compiler required member 'System.Object.Equals'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "Equals"),
// error CS0656: Missing compiler required member 'System.Object.ToString'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "ToString"),
// error CS0656: Missing compiler required member 'System.Object.GetHashCode'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "GetHashCode"),
// error CS0656: Missing compiler required member 'System.String.Format'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.String", "Format"));
}
[Fact, WorkItem(530365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530365")]
public void NoDebuggerBrowsableStateType()
{
var stateSource = @"
namespace System.Diagnostics
{
public enum DebuggerBrowsableState
{
Collapsed = 2,
Never = 0,
RootHidden = 3
}
}
";
var stateLib = CreateEmptyCompilation(stateSource, new[] { MinCorlibRef });
var attributeSource = @"
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=false)]
public sealed class DebuggerBrowsableAttribute : Attribute
{
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
}
}
}
";
var attributeLib = CreateEmptyCompilation(attributeSource, new[] { MinCorlibRef, stateLib.ToMetadataReference() });
var source = @"
class Program
{
static int Main()
{
var t = new { Test = 1 };
return 0;
}
}";
var comp = CreateEmptyCompilation(new[] { Parse(source), s_equalityComparerSourceTree }, new[] { MinCorlibRef, attributeLib.ToMetadataReference() });
var result = comp.Emit(new MemoryStream());
result.Diagnostics.Verify(
// error CS0656: Missing compiler required member 'System.Object.Equals'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "Equals"),
// error CS0656: Missing compiler required member 'System.Object.ToString'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "ToString"),
// error CS0656: Missing compiler required member 'System.Object.GetHashCode'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Object", "GetHashCode"),
// error CS0656: Missing compiler required member 'System.String.Format'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.String", "Format"));
}
[Fact]
public void ConditionalAccessErrors()
{
var source = @"
class C
{
int M() { return 0; }
void Test()
{
C local = null;
C[] array = null;
var x1 = new { local?.M() };
var x2 = new { array?[0] };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,24): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// var x1 = new { local?.M() };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "local?.M()").WithLocation(12, 24),
// (13,24): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// var x2 = new { array?[0] };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "array?[0]").WithLocation(13, 24));
}
[ClrOnlyFact]
[WorkItem(991505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991505")]
[WorkItem(199, "CodePlex")]
public void Bug991505()
{
var source = @"
class C
{
C P { get { return null; } }
int L { get { return 0; } }
int M { get { return 0; } }
int N { get { return 0; } }
void Test()
{
C local = null;
C[] array = null;
var x1 = new { local };
var x2_1 = new { local.P };
var x2_2 = new { local?.P };
var x3_1 = new { local.L };
var x3_2 = new { local?.L };
var x4_1 = new { local.P.M };
var x4_2 = new { local?.P.M };
var x4_3 = new { local?.P?.M };
var x5_1 = new { array[0].N };
var x5_2 = new { array?[0].N };
}
}
";
CompileAndVerify(
source,
symbolValidator: module =>
TestAnonymousTypeSymbols(
module,
new TypeDescr() { FieldNames = new[] { "local" } },
new TypeDescr() { FieldNames = new[] { "P" } },
new TypeDescr() { FieldNames = new[] { "L" } },
new TypeDescr() { FieldNames = new[] { "M" } },
new TypeDescr() { FieldNames = new[] { "N" } }));
}
[ClrOnlyFact]
public void CallingCreateAnonymousTypeDoesNotChangeIL()
{
var source = @"
class C
{
public static void Main(string[] args)
{
var v = new { m1 = 1, m2 = true };
}
}";
var expectedIL = @"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int, bool>..ctor(int, bool)""
IL_0007: pop
IL_0008: ret
}";
CompileAndVerify(source).VerifyIL("C.Main", expectedIL);
var compilation = CreateCompilationWithMscorlib40(source);
compilation.CreateAnonymousTypeSymbol(
ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32).GetPublicSymbol(), compilation.GetSpecialType(SpecialType.System_Boolean).GetPublicSymbol()),
ImmutableArray.Create("m1", "m2"));
this.CompileAndVerify(compilation).VerifyIL("C.Main", expectedIL);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/ICollection.NonGeneric.Tests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/ICollection.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// ICollection interface
/// </summary>
public abstract class ICollection_NonGeneric_Tests : IEnumerable_NonGeneric_Tests
{
#region Helper methods
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected abstract ICollection NonGenericICollectionFactory();
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned ICollection contains.</param>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected virtual ICollection NonGenericICollectionFactory(int count)
{
ICollection collection = NonGenericICollectionFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual bool DuplicateValuesAllowed => true;
protected virtual bool IsReadOnly => false;
protected virtual bool NullAllowed => true;
protected virtual bool ExpectedIsSynchronized => false;
protected virtual IEnumerable<object?> InvalidValues => new object?[0];
protected abstract void AddToCollection(ICollection collection, int numberOfItemsToAdd);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfEnumType test where we try to call CopyTo
/// on an Array of Enum values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType test where we try to call CopyTo
/// on an Array of different reference values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton or an ArrayTypeMismatchException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType test where we try to call CopyTo
/// on an Array of different value values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_NonZeroLowerBound test where we try to call CopyTo
/// on an Array of with a non-zero lower bound.
/// Most implementations throw an ArgumentException, but others (e.g. SortedList) throw
/// an ArgumentOutOfRangeException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. ConcurrentDictionary)
/// don't support the SyncRoot property of an ICollection and throw a NotSupportedException.
/// </summary>
protected virtual bool ICollection_NonGeneric_SupportsSyncRoot => true;
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. TempFileCollection)
/// return null for the SyncRoot property of an ICollection.
/// </summary>
protected virtual bool ICollection_NonGeneric_HasNullSyncRoot => false;
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsArgumentException tests. Some
/// implementations throw a different exception type (e.g. ArgumentOutOfRangeException).
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException test. Some implementations
/// throw a different exception type (e.g. RankException by ImmutableArray)
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType => typeof(ArgumentException);
#endregion
#region IEnumerable Helper Methods
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override IEnumerable NonGenericIEnumerableFactory(int count) => NonGenericICollectionFactory(count);
#endregion
#region Count
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_Count_Validity(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(count, collection.Count);
}
#endregion
#region IsSynchronized
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_IsSynchronized(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(ExpectedIsSynchronized, collection.IsSynchronized);
}
#endregion
#region SyncRoot
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRoot(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
if (ICollection_NonGeneric_SupportsSyncRoot)
{
Assert.Equal(ICollection_NonGeneric_HasNullSyncRoot, collection.SyncRoot == null);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
else
{
Assert.Throws<NotSupportedException>(() => collection.SyncRoot);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRootUnique(int count)
{
if (ICollection_NonGeneric_SupportsSyncRoot && !ICollection_NonGeneric_HasNullSyncRoot)
{
ICollection collection1 = NonGenericICollectionFactory(count);
ICollection collection2 = NonGenericICollectionFactory(count);
Assert.NotSame(collection1.SyncRoot, collection2.SyncRoot);
}
}
#endregion
#region CopyTo
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NullArray_ThrowsArgumentNullException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null!, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = new object[count, count];
Assert.Equal(2, arr.Rank);
Assert.Throws(ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType, () => collection.CopyTo(arr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 });
Assert.Equal(1, arr.Rank);
Assert.Equal(2, arr.GetLowerBound(0));
Assert.Throws(ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType, () => collection.CopyTo(arr, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
float[] array = new float[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
StringBuilder[] array = new StringBuilder[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfEnumType(int count)
{
Array enumArr = Enum.GetValues(typeof(EnumerableType));
if (count > 0 && count < enumArr.Length)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType, () => collection.CopyTo(enumArr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NegativeIndex_ThrowsArgumentOutOfRangeException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexEqualToArrayCount_ThrowsArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
if (count > 0)
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, count));
else
collection.CopyTo(array, count); // does nothing since the array is empty
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsAnyArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws(ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType, () => collection.CopyTo(array, count + 1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NotEnoughSpaceInOffsettedArray_ThrowsArgumentException(int count)
{
if (count > 0) // Want the T array to have at least 1 element
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, 1));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ExactlyEnoughSpaceInArray(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayIsLargerThanCollection(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count * 3 / 2];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/ICollection.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// ICollection interface
/// </summary>
public abstract class ICollection_NonGeneric_Tests : IEnumerable_NonGeneric_Tests
{
#region Helper methods
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected abstract ICollection NonGenericICollectionFactory();
/// <summary>
/// Creates an instance of an ICollection that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned ICollection contains.</param>
/// <returns>An instance of an ICollection that can be used for testing.</returns>
protected virtual ICollection NonGenericICollectionFactory(int count)
{
ICollection collection = NonGenericICollectionFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual bool DuplicateValuesAllowed => true;
protected virtual bool IsReadOnly => false;
protected virtual bool NullAllowed => true;
protected virtual bool ExpectedIsSynchronized => false;
protected virtual IEnumerable<object?> InvalidValues => new object?[0];
protected abstract void AddToCollection(ICollection collection, int numberOfItemsToAdd);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfEnumType test where we try to call CopyTo
/// on an Array of Enum values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType test where we try to call CopyTo
/// on an Array of different reference values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton or an ArrayTypeMismatchException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType test where we try to call CopyTo
/// on an Array of different value values. Some implementations special-case for this and throw an ArgumentException,
/// while others just throw an InvalidCastExcepton.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_NonZeroLowerBound test where we try to call CopyTo
/// on an Array of with a non-zero lower bound.
/// Most implementations throw an ArgumentException, but others (e.g. SortedList) throw
/// an ArgumentOutOfRangeException.
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. ConcurrentDictionary)
/// don't support the SyncRoot property of an ICollection and throw a NotSupportedException.
/// </summary>
protected virtual bool ICollection_NonGeneric_SupportsSyncRoot => true;
/// <summary>
/// Used for ICollection_NonGeneric_SyncRoot tests. Some implementations (e.g. TempFileCollection)
/// return null for the SyncRoot property of an ICollection.
/// </summary>
protected virtual bool ICollection_NonGeneric_HasNullSyncRoot => false;
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsArgumentException tests. Some
/// implementations throw a different exception type (e.g. ArgumentOutOfRangeException).
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentException);
/// <summary>
/// Used for the ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException test. Some implementations
/// throw a different exception type (e.g. RankException by ImmutableArray)
/// </summary>
protected virtual Type ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType => typeof(ArgumentException);
#endregion
#region IEnumerable Helper Methods
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>();
protected override IEnumerable NonGenericIEnumerableFactory(int count) => NonGenericICollectionFactory(count);
#endregion
#region Count
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_Count_Validity(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(count, collection.Count);
}
#endregion
#region IsSynchronized
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_IsSynchronized(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Equal(ExpectedIsSynchronized, collection.IsSynchronized);
}
#endregion
#region SyncRoot
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRoot(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
if (ICollection_NonGeneric_SupportsSyncRoot)
{
Assert.Equal(ICollection_NonGeneric_HasNullSyncRoot, collection.SyncRoot == null);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
else
{
Assert.Throws<NotSupportedException>(() => collection.SyncRoot);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_SyncRootUnique(int count)
{
if (ICollection_NonGeneric_SupportsSyncRoot && !ICollection_NonGeneric_HasNullSyncRoot)
{
ICollection collection1 = NonGenericICollectionFactory(count);
ICollection collection2 = NonGenericICollectionFactory(count);
Assert.NotSame(collection1.SyncRoot, collection2.SyncRoot);
}
}
#endregion
#region CopyTo
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NullArray_ThrowsArgumentNullException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null!, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowsException(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = new object[count, count];
Assert.Equal(2, arr.Rank);
Assert.Throws(ICollection_NonGeneric_CopyTo_TwoDimensionArray_ThrowType, () => collection.CopyTo(arr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 });
Assert.Equal(1, arr.Rank);
Assert.Equal(2, arr.GetLowerBound(0));
Assert.Throws(ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType, () => collection.CopyTo(arr, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
float[] array = new float[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType(int count)
{
if (count > 0)
{
ICollection collection = NonGenericICollectionFactory(count);
StringBuilder[] array = new StringBuilder[count * 3 / 2];
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType, () => collection.CopyTo(array, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_ArrayOfEnumType(int count)
{
Array enumArr = Enum.GetValues(typeof(EnumerableType));
if (count > 0 && count < enumArr.Length)
{
ICollection collection = NonGenericICollectionFactory(count);
Assert.Throws(ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType, () => collection.CopyTo(enumArr, 0));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_NegativeIndex_ThrowsArgumentOutOfRangeException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexEqualToArrayCount_ThrowsArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
if (count > 0)
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, count));
else
collection.CopyTo(array, count); // does nothing since the array is empty
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowsAnyArgumentException(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws(ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType, () => collection.CopyTo(array, count + 1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public virtual void ICollection_NonGeneric_CopyTo_NotEnoughSpaceInOffsettedArray_ThrowsArgumentException(int count)
{
if (count > 0) // Want the T array to have at least 1 element
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
Assert.Throws<ArgumentException>(() => collection.CopyTo(array, 1));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ExactlyEnoughSpaceInArray(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayIsLargerThanCollection(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
object[] array = new object[count * 3 / 2];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/IIgnorableAssemblyList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal interface IIgnorableAssemblyList
{
bool Includes(AssemblyIdentity assemblyIdentity);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal interface IIgnorableAssemblyList
{
bool Includes(AssemblyIdentity assemblyIdentity);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/Core/Portable/CodeCleanup/ICodeCleanerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeCleanup.Providers;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
/// <summary>
/// Internal code cleanup service interface.
///
/// This is not supposed to be used directly. It just provides a way to get the right service from each language.
/// </summary>
internal interface ICodeCleanerService : ILanguageService
{
/// <summary>
/// Returns the default code cleaners.
/// </summary>
ImmutableArray<ICodeCleanupProvider> GetDefaultProviders();
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
/// </summary>
Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, ImmutableArray<ICodeCleanupProvider> providers, CancellationToken cancellationToken);
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
///
/// This will do cleanups that don't require any semantic information.
/// </summary>
Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, ImmutableArray<ICodeCleanupProvider> providers, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeCleanup.Providers;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
/// <summary>
/// Internal code cleanup service interface.
///
/// This is not supposed to be used directly. It just provides a way to get the right service from each language.
/// </summary>
internal interface ICodeCleanerService : ILanguageService
{
/// <summary>
/// Returns the default code cleaners.
/// </summary>
ImmutableArray<ICodeCleanupProvider> GetDefaultProviders();
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
/// </summary>
Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, ImmutableArray<ICodeCleanupProvider> providers, CancellationToken cancellationToken);
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
///
/// This will do cleanups that don't require any semantic information.
/// </summary>
Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, ImmutableArray<ICodeCleanupProvider> providers, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/Snippets/SnippetFunctions/AbstractSnippetFunctionSimpleTypeName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions
{
internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction
{
private readonly string _fieldName;
private readonly string _fullyQualifiedName;
public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName)
: base(snippetExpansionClient, subjectBuffer)
{
_fieldName = fieldName;
_fullyQualifiedName = fullyQualifiedName;
}
protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
value = _fullyQualifiedName;
hasDefaultValue = 1;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName))
{
return VSConstants.E_FAIL;
}
if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName))
{
return VSConstants.E_FAIL;
}
value = simplifiedName;
hasDefaultValue = 1;
return VSConstants.S_OK;
}
private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, out Document documentWithFullyQualifiedTypeName)
{
documentWithFullyQualifiedTypeName = null;
updatedTextSpan = default;
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return false;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return false;
}
var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length);
updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length);
var textChange = new TextChange(originalTextSpan, _fullyQualifiedName);
var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange);
documentWithFullyQualifiedTypeName = document.WithText(newText);
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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions
{
internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction
{
private readonly string _fieldName;
private readonly string _fullyQualifiedName;
public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName)
: base(snippetExpansionClient, subjectBuffer)
{
_fieldName = fieldName;
_fullyQualifiedName = fullyQualifiedName;
}
protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
value = _fullyQualifiedName;
hasDefaultValue = 1;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName))
{
return VSConstants.E_FAIL;
}
if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName))
{
return VSConstants.E_FAIL;
}
value = simplifiedName;
hasDefaultValue = 1;
return VSConstants.S_OK;
}
private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, out Document documentWithFullyQualifiedTypeName)
{
documentWithFullyQualifiedTypeName = null;
updatedTextSpan = default;
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return false;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return false;
}
var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length);
updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length);
var textChange = new TextChange(originalTextSpan, _fullyQualifiedName);
var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange);
documentWithFullyQualifiedTypeName = document.WithText(newText);
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Helpers/RemoveUnnecessaryImports/IUnnecessaryImportsProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports
{
internal interface IUnnecessaryImportsProvider
{
ImmutableArray<SyntaxNode> GetUnnecessaryImports(SemanticModel model, CancellationToken cancellationToken);
ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model,
SyntaxNode root,
Func<SyntaxNode, bool> predicate,
CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports
{
internal interface IUnnecessaryImportsProvider
{
ImmutableArray<SyntaxNode> GetUnnecessaryImports(SemanticModel model, CancellationToken cancellationToken);
ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model,
SyntaxNode root,
Func<SyntaxNode, bool> predicate,
CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
[UseExportProvider]
public partial class CodeGenerationTests
{
internal static async Task TestAddNamespaceAsync(
string initial,
string expected,
string name = "N",
IList<ISymbol> imports = null,
IList<INamespaceOrTypeSymbol> members = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var @namespace = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name, imports, members);
context.Result = await context.Service.AddNamespaceAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), @namespace, codeGenerationOptions);
}
internal static async Task TestAddFieldAsync(
string initial,
string expected,
Func<SemanticModel, ITypeSymbol> type = null,
string name = "F",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
CodeGenerationOptions codeGenerationOptions = null,
bool hasConstantValue = false,
object constantValue = null,
bool addToCompilationUnit = false)
{
using var context = await TestContext.CreateAsync(initial, expected);
var typeSymbol = type != null ? type(context.SemanticModel) : null;
var field = CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility,
modifiers,
typeSymbol,
name,
hasConstantValue,
constantValue);
if (!addToCompilationUnit)
{
context.Result = await context.Service.AddFieldAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), field, codeGenerationOptions);
}
else
{
var newRoot = context.Service.AddField(await context.Document.GetSyntaxRootAsync(), field, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot(newRoot);
}
}
internal static async Task TestAddConstructorAsync(
string initial,
string expected,
string name = "C",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
ImmutableArray<SyntaxNode> statements = default,
ImmutableArray<SyntaxNode> baseArguments = default,
ImmutableArray<SyntaxNode> thisArguments = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var ctor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility,
modifiers,
name,
parameterSymbols,
statements,
baseConstructorArguments: baseArguments,
thisConstructorArguments: thisArguments);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), ctor, codeGenerationOptions);
}
internal static async Task TestAddMethodAsync(
string initial,
string expected,
string name = "M",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
Func<SemanticModel, ImmutableArray<IMethodSymbol>> getExplicitInterfaces = null,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
ImmutableArray<SyntaxNode> handlesExpressions = default,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var explicitInterfaceImplementations = GetMethodSymbols(getExplicitInterfaces, context);
var method = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
RefKind.None,
explicitInterfaceImplementations,
name,
typeParameters,
parameterSymbols,
parsedStatements,
handlesExpressions: handlesExpressions);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
internal static async Task TestAddOperatorsAsync(
string initial,
string expected,
CodeGenerationOperatorKind[] operatorKinds,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
while (expected.IndexOf("$$", StringComparison.Ordinal) != -1)
{
expected = expected.Replace("$$", statements);
}
}
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var methods = operatorKinds.Select(kind => CodeGenerationSymbolFactory.CreateOperatorSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
kind,
parameterSymbols,
parsedStatements));
context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), methods.ToArray(), codeGenerationOptions);
}
internal static async Task TestAddUnsupportedOperatorAsync(
string initial,
CodeGenerationOperatorKind operatorKind,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, initial, ignoreResult: true);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var method = CodeGenerationSymbolFactory.CreateOperatorSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
operatorKind,
parameterSymbols,
parsedStatements);
ArgumentException exception = null;
try
{
await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
catch (ArgumentException e)
{
exception = e;
}
var expectedMessage = string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name);
Assert.True(exception != null && exception.Message.StartsWith(expectedMessage, StringComparison.Ordinal),
string.Format("\r\nExpected exception: {0}\r\nActual exception: {1}\r\n", expectedMessage, exception == null ? "no exception" : exception.Message));
}
internal static async Task TestAddConversionAsync(
string initial,
string expected,
Type toType,
Func<SemanticModel, IParameterSymbol> fromType,
bool isImplicit = false,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parsedStatements = context.ParseStatements(statements);
var method = CodeGenerationSymbolFactory.CreateConversionSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(toType)(context.SemanticModel),
fromType(context.SemanticModel),
containingType: null,
isImplicit,
parsedStatements);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
internal static async Task TestAddStatementsAsync(
string initial,
string expected,
string statements,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parsedStatements = context.ParseStatements(statements);
var oldSyntax = context.GetSelectedSyntax<SyntaxNode>(true);
var newSyntax = context.Service.AddStatements(oldSyntax, parsedStatements, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldSyntax, newSyntax));
}
internal static async Task TestAddParametersAsync(
string initial,
string expected,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var oldMemberSyntax = context.GetSelectedSyntax<SyntaxNode>(true);
var newMemberSyntax = context.Service.AddParameters(oldMemberSyntax, parameterSymbols, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldMemberSyntax, newMemberSyntax));
}
internal static async Task TestAddDelegateTypeAsync(
string initial,
string expected,
string name = "D",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var type = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
RefKind.None,
name,
typeParameters,
parameterSymbols);
context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), type, codeGenerationOptions);
}
internal static async Task TestAddEventAsync(
string initial,
string expected,
string name = "E",
ImmutableArray<AttributeData> attributes = default,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
Type type = null,
Func<SemanticModel, ImmutableArray<IEventSymbol>> getExplicitInterfaceImplementations = null,
IMethodSymbol addMethod = null,
IMethodSymbol removeMethod = null,
IMethodSymbol raiseMethod = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
type ??= typeof(Action);
var parameterSymbols = GetParameterSymbols(parameters, context);
var typeSymbol = GetTypeSymbol(type)(context.SemanticModel);
var @event = CodeGenerationSymbolFactory.CreateEventSymbol(
attributes,
accessibility,
modifiers,
typeSymbol,
getExplicitInterfaceImplementations?.Invoke(context.SemanticModel) ?? default,
name,
addMethod,
removeMethod,
raiseMethod);
context.Result = await context.Service.AddEventAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), @event, codeGenerationOptions);
}
internal static async Task TestAddPropertyAsync(
string initial,
string expected,
string name = "P",
Accessibility defaultAccessibility = Accessibility.Public,
Accessibility setterAccessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
string getStatements = null,
string setStatements = null,
Type type = null,
ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
bool isIndexer = false,
CodeGenerationOptions codeGenerationOptions = null,
IDictionary<OptionKey2, object> options = null)
{
// This assumes that tests will not use place holders for get/set statements at the same time
if (getStatements != null)
{
expected = expected.Replace("$$", getStatements);
}
if (setStatements != null)
{
expected = expected.Replace("$$", setStatements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var workspace = context.Workspace;
if (options != null)
{
var optionSet = workspace.Options;
foreach (var (key, value) in options)
optionSet = optionSet.WithChangedOption(key, value);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet));
}
var typeSymbol = GetTypeSymbol(type)(context.SemanticModel);
var getParameterSymbols = GetParameterSymbols(parameters, context);
var setParameterSymbols = getParameterSymbols == null
? default
: getParameterSymbols.Add(Parameter(type, "value")(context.SemanticModel));
var getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
defaultAccessibility,
new Editing.DeclarationModifiers(isAbstract: getStatements == null),
typeSymbol,
RefKind.None,
explicitInterfaceImplementations: default,
"get_" + name,
typeParameters: default,
getParameterSymbols,
statements: context.ParseStatements(getStatements));
var setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
setterAccessibility,
new Editing.DeclarationModifiers(isAbstract: setStatements == null),
GetTypeSymbol(typeof(void))(context.SemanticModel),
RefKind.None,
explicitInterfaceImplementations: default,
"set_" + name,
typeParameters: default,
setParameterSymbols,
statements: context.ParseStatements(setStatements));
// If get is provided but set isn't, we don't want an accessor for set
if (getStatements != null && setStatements == null)
{
setAccessor = null;
}
// If set is provided but get isn't, we don't want an accessor for get
if (getStatements == null && setStatements != null)
{
getAccessor = null;
}
var property = CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
defaultAccessibility,
modifiers,
typeSymbol,
RefKind.None,
explicitInterfaceImplementations,
name,
getParameterSymbols,
getAccessor,
setAccessor,
isIndexer);
codeGenerationOptions ??= new CodeGenerationOptions();
codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? workspace.Options);
context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions);
}
internal static async Task TestAddNamedTypeAsync(
string initial,
string expected,
string name = "C",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
TypeKind typeKind = TypeKind.Class,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
INamedTypeSymbol baseType = null,
ImmutableArray<INamedTypeSymbol> interfaces = default,
SpecialType specialType = SpecialType.None,
ImmutableArray<Func<SemanticModel, ISymbol>> members = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var memberSymbols = GetSymbols(members, context);
var type = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default, accessibility, modifiers, typeKind, name,
typeParameters, baseType, interfaces, specialType, memberSymbols);
context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), type, codeGenerationOptions);
}
internal static async Task TestAddAttributeAsync(
string initial,
string expected,
Type attributeClass,
SyntaxToken? target = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var attr = CodeGenerationSymbolFactory.CreateAttributeData((INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel));
var oldNode = context.GetDestinationNode();
var newNode = CodeGenerator.AddAttributes(oldNode, context.Document.Project.Solution.Workspace, new[] { attr }, target)
.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(oldNode, newNode));
}
internal static async Task TestRemoveAttributeAsync<T>(
string initial,
string expected,
Type attributeClass) where T : SyntaxNode
{
using var context = await TestContext.CreateAsync(initial, expected);
var attributeType = (INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel);
var taggedNode = context.GetDestinationNode();
var attributeTarget = context.SemanticModel.GetDeclaredSymbol(taggedNode);
var attribute = attributeTarget.GetAttributes().Single(attr => Equals(attr.AttributeClass, attributeType));
var declarationNode = taggedNode.FirstAncestorOrSelf<T>();
var newNode = CodeGenerator.RemoveAttribute(declarationNode, context.Document.Project.Solution.Workspace, attribute)
.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, newNode));
}
internal static async Task TestUpdateDeclarationAsync<T>(
string initial,
string expected,
Accessibility? accessibility = null,
IEnumerable<SyntaxToken> modifiers = null,
Func<SemanticModel, ITypeSymbol> getType = null,
ImmutableArray<Func<SemanticModel, ISymbol>> getNewMembers = default,
bool? declareNewMembersAtTop = null,
string retainedMembersKey = "RetainedMember") where T : SyntaxNode
{
using var context = await TestContext.CreateAsync(initial, expected);
var declarationNode = context.GetDestinationNode().FirstAncestorOrSelf<T>();
var updatedDeclarationNode = declarationNode;
var workspace = context.Document.Project.Solution.Workspace;
if (accessibility.HasValue)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationAccessibility(declarationNode, workspace, accessibility.Value);
}
else if (modifiers != null)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationModifiers(declarationNode, workspace, modifiers);
}
else if (getType != null)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationType(declarationNode, workspace, getType(context.SemanticModel));
}
else if (getNewMembers != null)
{
var retainedMembers = context.GetAnnotatedDeclaredSymbols(retainedMembersKey, context.SemanticModel);
var newMembersToAdd = GetSymbols(getNewMembers, context);
var allMembers = new List<ISymbol>();
if (declareNewMembersAtTop.HasValue && declareNewMembersAtTop.Value)
{
allMembers.AddRange(newMembersToAdd);
allMembers.AddRange(retainedMembers);
}
else
{
allMembers.AddRange(retainedMembers);
allMembers.AddRange(newMembersToAdd);
}
updatedDeclarationNode = CodeGenerator.UpdateDeclarationMembers(declarationNode, workspace, allMembers);
}
updatedDeclarationNode = updatedDeclarationNode.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, updatedDeclarationNode));
}
internal static async Task TestGenerateFromSourceSymbolAsync(
string symbolSource,
string initial,
string expected,
bool onlyGenerateMembers = false,
CodeGenerationOptions codeGenerationOptions = null,
string forceLanguage = null)
{
using var context = await TestContext.CreateAsync(initial, expected, forceLanguage);
var destSpan = new TextSpan();
MarkupTestFile.GetSpan(symbolSource.NormalizeLineEndings(), out symbolSource, out destSpan);
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
var semanticModel = await context.Solution
.AddProject(projectId, "GenerationSource", "GenerationSource", TestContext.GetLanguage(symbolSource))
.AddDocument(documentId, "Source.cs", symbolSource)
.GetDocument(documentId)
.GetSemanticModelAsync();
var docOptions = await context.Document.GetOptionsAsync();
codeGenerationOptions ??= new CodeGenerationOptions();
codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? docOptions);
var symbol = TestContext.GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, semanticModel);
var destination = context.GetDestination();
if (destination.IsType)
{
var members = onlyGenerateMembers ? symbol.GetMembers().ToArray() : new[] { symbol };
context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)destination, members, codeGenerationOptions);
}
else
{
context.Result = await context.Service.AddNamespaceOrTypeAsync(context.Solution, (INamespaceSymbol)destination, symbol, codeGenerationOptions);
}
}
internal static Func<SemanticModel, IParameterSymbol> Parameter(Type type, string name, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false)
{
return s => CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, type), name,
isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue);
}
internal static Func<SemanticModel, IParameterSymbol> Parameter(string typeFullName, string parameterName, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false, int typeArrayRank = 0)
{
return s => CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, typeFullName, typeArrayRank), parameterName,
isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue);
}
private static ITypeSymbol GetTypeSymbol(Compilation compilation, Type type)
=> !type.IsArray ? GetTypeSymbol(compilation, type.FullName) : GetTypeSymbol(compilation, type.GetElementType().FullName, type.GetArrayRank());
private static ITypeSymbol GetTypeSymbol(Compilation compilation, string typeFullName, int arrayRank = 0)
{
return arrayRank == 0 ? (ITypeSymbol)compilation.GetTypeByMetadataName(typeFullName)
: compilation.CreateArrayTypeSymbol(compilation.GetTypeByMetadataName(typeFullName), arrayRank);
}
internal static ImmutableArray<Func<SemanticModel, IParameterSymbol>> Parameters(params Func<SemanticModel, IParameterSymbol>[] p)
=> p.ToImmutableArray();
internal static ImmutableArray<Func<SemanticModel, ISymbol>> Members(params Func<SemanticModel, ISymbol>[] m)
=> m.ToImmutableArray();
internal static Func<SemanticModel, ITypeSymbol> CreateArrayType(Type type, int rank = 1)
=> s => CodeGenerationSymbolFactory.CreateArrayTypeSymbol(GetTypeSymbol(type)(s), rank);
private static ImmutableArray<IParameterSymbol> GetParameterSymbols(ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, TestContext context)
=> parameters.IsDefault
? default
: parameters.SelectAsArray(p => p(context.SemanticModel));
private static ImmutableArray<IMethodSymbol> GetMethodSymbols(
Func<SemanticModel, ImmutableArray<IMethodSymbol>> explicitInterface, TestContext context)
{
return explicitInterface == null ? default : explicitInterface(context.SemanticModel);
}
private static ImmutableArray<ISymbol> GetSymbols(ImmutableArray<Func<SemanticModel, ISymbol>> members, TestContext context)
{
return members == null
? default
: members.SelectAsArray(m => m(context.SemanticModel));
}
private static Func<SemanticModel, ISymbol> CreateEnumField(string name, object value)
{
return s => CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default, Accessibility.Public,
new Editing.DeclarationModifiers(), GetTypeSymbol(typeof(int))(s), name, value != null, value);
}
internal static Func<SemanticModel, ISymbol> CreateField(Accessibility accessibility, Editing.DeclarationModifiers modifiers, Type type, string name)
{
return s => CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default, accessibility,
modifiers, GetTypeSymbol(type)(s), name);
}
private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(Type type)
=> GetTypeSymbol(type.FullName);
private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(string typeMetadataName)
=> s => s?.Compilation.GetTypeByMetadataName(typeMetadataName);
internal static IEnumerable<SyntaxToken> CreateModifierTokens(Editing.DeclarationModifiers modifiers, string language)
{
if (language == LanguageNames.CSharp)
{
if (modifiers.IsAbstract)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AbstractKeyword);
}
if (modifiers.IsAsync)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AsyncKeyword);
}
if (modifiers.IsConst)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ConstKeyword);
}
if (modifiers.IsNew)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.NewKeyword);
}
if (modifiers.IsOverride)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.OverrideKeyword);
}
if (modifiers.IsPartial)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.PartialKeyword);
}
if (modifiers.IsReadOnly)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ReadOnlyKeyword);
}
if (modifiers.IsSealed)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.SealedKeyword);
}
if (modifiers.IsStatic)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.StaticKeyword);
}
if (modifiers.IsUnsafe)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.UnsafeKeyword);
}
if (modifiers.IsVirtual)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.VirtualKeyword);
}
}
else
{
if (modifiers.IsAbstract)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.MustOverrideKeyword);
}
if (modifiers.IsAsync)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.AsyncKeyword);
}
if (modifiers.IsConst)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ConstKeyword);
}
if (modifiers.IsNew)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NewKeyword);
}
if (modifiers.IsOverride)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridesKeyword);
}
if (modifiers.IsPartial)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.PartialKeyword);
}
if (modifiers.IsReadOnly)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ReadOnlyKeyword);
}
if (modifiers.IsSealed)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NotInheritableKeyword);
}
if (modifiers.IsStatic)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.StaticKeyword);
}
if (modifiers.IsVirtual)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridableKeyword);
}
}
}
internal class TestContext : IDisposable
{
private readonly string _expected;
public readonly bool IsVisualBasic;
public Document Document;
public SemanticModel SemanticModel;
public SyntaxTree SyntaxTree;
public ICodeGenerationService Service;
public Document Result;
public readonly TestWorkspace Workspace;
private readonly string _language;
private readonly bool _ignoreResult;
public TestContext(
string expected,
bool ignoreResult,
string language,
TestWorkspace workspace,
SemanticModel semanticModel)
{
_expected = expected.NormalizeLineEndings();
_language = language;
this.IsVisualBasic = _language == LanguageNames.VisualBasic;
_ignoreResult = ignoreResult;
Workspace = workspace;
this.Document = Workspace.CurrentSolution.Projects.Single().Documents.Single();
this.SemanticModel = semanticModel;
this.SyntaxTree = SemanticModel.SyntaxTree;
this.Service = Document.Project.LanguageServices.GetService<ICodeGenerationService>();
}
public static async Task<TestContext> CreateAsync(string initial, string expected, string forceLanguage = null, bool ignoreResult = false)
{
var language = forceLanguage ?? GetLanguage(initial);
var isVisualBasic = language == LanguageNames.VisualBasic;
var workspace = CreateWorkspaceFromFile(initial.NormalizeLineEndings(), isVisualBasic, null, null);
var semanticModel = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetSemanticModelAsync();
return new TestContext(expected, ignoreResult, language, workspace, semanticModel);
}
public Solution Solution { get { return Workspace.CurrentSolution; } }
public SyntaxNode GetDestinationNode()
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
return SemanticModel.SyntaxTree.GetRoot().FindNode(destSpan, getInnermostNodeForTie: true);
}
public INamespaceOrTypeSymbol GetDestination()
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
return GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, this.SemanticModel);
}
public IEnumerable<ISymbol> GetAnnotatedDeclaredSymbols(string key, SemanticModel semanticModel)
{
var annotatedSpans = Workspace.Documents.Single().AnnotatedSpans[key];
foreach (var span in annotatedSpans)
{
yield return GetSelectedSymbol<ISymbol>(span, semanticModel);
}
}
public static T GetSelectedSymbol<T>(TextSpan selection, SemanticModel semanticModel)
where T : class, ISymbol
{
var token = semanticModel.SyntaxTree.GetRoot().FindToken(selection.Start);
var symbol = token.Parent.AncestorsAndSelf()
.Select(a => semanticModel.GetDeclaredSymbol(a))
.Where(s => s != null).FirstOrDefault() as T;
return symbol;
}
public T GetSelectedSyntax<T>(bool fullSpanCoverage = false) where T : SyntaxNode
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
var token = SemanticModel.SyntaxTree.GetRoot().FindToken(destSpan.Start);
return token.Parent.AncestorsAndSelf().OfType<T>().FirstOrDefault(t => !fullSpanCoverage || t.Span.End >= destSpan.End);
}
public ImmutableArray<SyntaxNode> ParseStatements(string statements)
{
if (statements == null)
{
return default;
}
using var listDisposer = ArrayBuilder<SyntaxNode>.GetInstance(out var list);
var delimiter = IsVisualBasic ? "\r\n" : ";";
var parts = statements.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (var p in parts)
{
if (IsVisualBasic)
{
list.Add(VB.SyntaxFactory.ParseExecutableStatement(p));
}
else
{
list.Add(CS.SyntaxFactory.ParseStatement(p + delimiter));
}
}
return list.ToImmutable();
}
public void Dispose()
{
try
{
if (!_ignoreResult)
{
this.Document = this.Result;
var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result
.GetSyntaxRootAsync().Result.ToFullString();
Assert.Equal(_expected, actual);
}
}
finally
{
Workspace.Dispose();
}
}
public static string GetLanguage(string input)
{
return ContainsVisualBasicKeywords(input)
? LanguageNames.VisualBasic : LanguageNames.CSharp;
}
private static bool ContainsVisualBasicKeywords(string input)
{
return
input.Contains("Module") ||
input.Contains("Class") ||
input.Contains("Structure") ||
input.Contains("Namespace") ||
input.Contains("Sub") ||
input.Contains("Function") ||
input.Contains("Dim") ||
input.Contains("Enum");
}
private static TestWorkspace CreateWorkspaceFromFile(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions)
{
return isVisualBasic ?
TestWorkspace.CreateVisualBasic(file, (VB.VisualBasicParseOptions)parseOptions, (VB.VisualBasicCompilationOptions)compilationOptions) :
TestWorkspace.CreateCSharp(file, (CS.CSharpParseOptions)parseOptions, (CS.CSharpCompilationOptions)compilationOptions);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
[UseExportProvider]
public partial class CodeGenerationTests
{
internal static async Task TestAddNamespaceAsync(
string initial,
string expected,
string name = "N",
IList<ISymbol> imports = null,
IList<INamespaceOrTypeSymbol> members = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var @namespace = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name, imports, members);
context.Result = await context.Service.AddNamespaceAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), @namespace, codeGenerationOptions);
}
internal static async Task TestAddFieldAsync(
string initial,
string expected,
Func<SemanticModel, ITypeSymbol> type = null,
string name = "F",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
CodeGenerationOptions codeGenerationOptions = null,
bool hasConstantValue = false,
object constantValue = null,
bool addToCompilationUnit = false)
{
using var context = await TestContext.CreateAsync(initial, expected);
var typeSymbol = type != null ? type(context.SemanticModel) : null;
var field = CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility,
modifiers,
typeSymbol,
name,
hasConstantValue,
constantValue);
if (!addToCompilationUnit)
{
context.Result = await context.Service.AddFieldAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), field, codeGenerationOptions);
}
else
{
var newRoot = context.Service.AddField(await context.Document.GetSyntaxRootAsync(), field, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot(newRoot);
}
}
internal static async Task TestAddConstructorAsync(
string initial,
string expected,
string name = "C",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
ImmutableArray<SyntaxNode> statements = default,
ImmutableArray<SyntaxNode> baseArguments = default,
ImmutableArray<SyntaxNode> thisArguments = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var ctor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility,
modifiers,
name,
parameterSymbols,
statements,
baseConstructorArguments: baseArguments,
thisConstructorArguments: thisArguments);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), ctor, codeGenerationOptions);
}
internal static async Task TestAddMethodAsync(
string initial,
string expected,
string name = "M",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
Func<SemanticModel, ImmutableArray<IMethodSymbol>> getExplicitInterfaces = null,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
ImmutableArray<SyntaxNode> handlesExpressions = default,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var explicitInterfaceImplementations = GetMethodSymbols(getExplicitInterfaces, context);
var method = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
RefKind.None,
explicitInterfaceImplementations,
name,
typeParameters,
parameterSymbols,
parsedStatements,
handlesExpressions: handlesExpressions);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
internal static async Task TestAddOperatorsAsync(
string initial,
string expected,
CodeGenerationOperatorKind[] operatorKinds,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
while (expected.IndexOf("$$", StringComparison.Ordinal) != -1)
{
expected = expected.Replace("$$", statements);
}
}
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var methods = operatorKinds.Select(kind => CodeGenerationSymbolFactory.CreateOperatorSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
kind,
parameterSymbols,
parsedStatements));
context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), methods.ToArray(), codeGenerationOptions);
}
internal static async Task TestAddUnsupportedOperatorAsync(
string initial,
CodeGenerationOperatorKind operatorKind,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, initial, ignoreResult: true);
var parameterSymbols = GetParameterSymbols(parameters, context);
var parsedStatements = context.ParseStatements(statements);
var method = CodeGenerationSymbolFactory.CreateOperatorSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
operatorKind,
parameterSymbols,
parsedStatements);
ArgumentException exception = null;
try
{
await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
catch (ArgumentException e)
{
exception = e;
}
var expectedMessage = string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name);
Assert.True(exception != null && exception.Message.StartsWith(expectedMessage, StringComparison.Ordinal),
string.Format("\r\nExpected exception: {0}\r\nActual exception: {1}\r\n", expectedMessage, exception == null ? "no exception" : exception.Message));
}
internal static async Task TestAddConversionAsync(
string initial,
string expected,
Type toType,
Func<SemanticModel, IParameterSymbol> fromType,
bool isImplicit = false,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
string statements = null,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parsedStatements = context.ParseStatements(statements);
var method = CodeGenerationSymbolFactory.CreateConversionSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(toType)(context.SemanticModel),
fromType(context.SemanticModel),
containingType: null,
isImplicit,
parsedStatements);
context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions);
}
internal static async Task TestAddStatementsAsync(
string initial,
string expected,
string statements,
CodeGenerationOptions codeGenerationOptions = null)
{
if (statements != null)
{
expected = expected.Replace("$$", statements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var parsedStatements = context.ParseStatements(statements);
var oldSyntax = context.GetSelectedSyntax<SyntaxNode>(true);
var newSyntax = context.Service.AddStatements(oldSyntax, parsedStatements, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldSyntax, newSyntax));
}
internal static async Task TestAddParametersAsync(
string initial,
string expected,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var oldMemberSyntax = context.GetSelectedSyntax<SyntaxNode>(true);
var newMemberSyntax = context.Service.AddParameters(oldMemberSyntax, parameterSymbols, codeGenerationOptions);
context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldMemberSyntax, newMemberSyntax));
}
internal static async Task TestAddDelegateTypeAsync(
string initial,
string expected,
string name = "D",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
Type returnType = null,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var parameterSymbols = GetParameterSymbols(parameters, context);
var type = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
attributes: default,
accessibility,
modifiers,
GetTypeSymbol(returnType)(context.SemanticModel),
RefKind.None,
name,
typeParameters,
parameterSymbols);
context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), type, codeGenerationOptions);
}
internal static async Task TestAddEventAsync(
string initial,
string expected,
string name = "E",
ImmutableArray<AttributeData> attributes = default,
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
Type type = null,
Func<SemanticModel, ImmutableArray<IEventSymbol>> getExplicitInterfaceImplementations = null,
IMethodSymbol addMethod = null,
IMethodSymbol removeMethod = null,
IMethodSymbol raiseMethod = null,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
type ??= typeof(Action);
var parameterSymbols = GetParameterSymbols(parameters, context);
var typeSymbol = GetTypeSymbol(type)(context.SemanticModel);
var @event = CodeGenerationSymbolFactory.CreateEventSymbol(
attributes,
accessibility,
modifiers,
typeSymbol,
getExplicitInterfaceImplementations?.Invoke(context.SemanticModel) ?? default,
name,
addMethod,
removeMethod,
raiseMethod);
context.Result = await context.Service.AddEventAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), @event, codeGenerationOptions);
}
internal static async Task TestAddPropertyAsync(
string initial,
string expected,
string name = "P",
Accessibility defaultAccessibility = Accessibility.Public,
Accessibility setterAccessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
string getStatements = null,
string setStatements = null,
Type type = null,
ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default,
ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default,
bool isIndexer = false,
CodeGenerationOptions codeGenerationOptions = null,
IDictionary<OptionKey2, object> options = null)
{
// This assumes that tests will not use place holders for get/set statements at the same time
if (getStatements != null)
{
expected = expected.Replace("$$", getStatements);
}
if (setStatements != null)
{
expected = expected.Replace("$$", setStatements);
}
using var context = await TestContext.CreateAsync(initial, expected);
var workspace = context.Workspace;
if (options != null)
{
var optionSet = workspace.Options;
foreach (var (key, value) in options)
optionSet = optionSet.WithChangedOption(key, value);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet));
}
var typeSymbol = GetTypeSymbol(type)(context.SemanticModel);
var getParameterSymbols = GetParameterSymbols(parameters, context);
var setParameterSymbols = getParameterSymbols == null
? default
: getParameterSymbols.Add(Parameter(type, "value")(context.SemanticModel));
var getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
defaultAccessibility,
new Editing.DeclarationModifiers(isAbstract: getStatements == null),
typeSymbol,
RefKind.None,
explicitInterfaceImplementations: default,
"get_" + name,
typeParameters: default,
getParameterSymbols,
statements: context.ParseStatements(getStatements));
var setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
setterAccessibility,
new Editing.DeclarationModifiers(isAbstract: setStatements == null),
GetTypeSymbol(typeof(void))(context.SemanticModel),
RefKind.None,
explicitInterfaceImplementations: default,
"set_" + name,
typeParameters: default,
setParameterSymbols,
statements: context.ParseStatements(setStatements));
// If get is provided but set isn't, we don't want an accessor for set
if (getStatements != null && setStatements == null)
{
setAccessor = null;
}
// If set is provided but get isn't, we don't want an accessor for get
if (getStatements == null && setStatements != null)
{
getAccessor = null;
}
var property = CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
defaultAccessibility,
modifiers,
typeSymbol,
RefKind.None,
explicitInterfaceImplementations,
name,
getParameterSymbols,
getAccessor,
setAccessor,
isIndexer);
codeGenerationOptions ??= new CodeGenerationOptions();
codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? workspace.Options);
context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions);
}
internal static async Task TestAddNamedTypeAsync(
string initial,
string expected,
string name = "C",
Accessibility accessibility = Accessibility.Public,
Editing.DeclarationModifiers modifiers = default,
TypeKind typeKind = TypeKind.Class,
ImmutableArray<ITypeParameterSymbol> typeParameters = default,
INamedTypeSymbol baseType = null,
ImmutableArray<INamedTypeSymbol> interfaces = default,
SpecialType specialType = SpecialType.None,
ImmutableArray<Func<SemanticModel, ISymbol>> members = default,
CodeGenerationOptions codeGenerationOptions = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var memberSymbols = GetSymbols(members, context);
var type = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default, accessibility, modifiers, typeKind, name,
typeParameters, baseType, interfaces, specialType, memberSymbols);
context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), type, codeGenerationOptions);
}
internal static async Task TestAddAttributeAsync(
string initial,
string expected,
Type attributeClass,
SyntaxToken? target = null)
{
using var context = await TestContext.CreateAsync(initial, expected);
var attr = CodeGenerationSymbolFactory.CreateAttributeData((INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel));
var oldNode = context.GetDestinationNode();
var newNode = CodeGenerator.AddAttributes(oldNode, context.Document.Project.Solution.Workspace, new[] { attr }, target)
.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(oldNode, newNode));
}
internal static async Task TestRemoveAttributeAsync<T>(
string initial,
string expected,
Type attributeClass) where T : SyntaxNode
{
using var context = await TestContext.CreateAsync(initial, expected);
var attributeType = (INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel);
var taggedNode = context.GetDestinationNode();
var attributeTarget = context.SemanticModel.GetDeclaredSymbol(taggedNode);
var attribute = attributeTarget.GetAttributes().Single(attr => Equals(attr.AttributeClass, attributeType));
var declarationNode = taggedNode.FirstAncestorOrSelf<T>();
var newNode = CodeGenerator.RemoveAttribute(declarationNode, context.Document.Project.Solution.Workspace, attribute)
.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, newNode));
}
internal static async Task TestUpdateDeclarationAsync<T>(
string initial,
string expected,
Accessibility? accessibility = null,
IEnumerable<SyntaxToken> modifiers = null,
Func<SemanticModel, ITypeSymbol> getType = null,
ImmutableArray<Func<SemanticModel, ISymbol>> getNewMembers = default,
bool? declareNewMembersAtTop = null,
string retainedMembersKey = "RetainedMember") where T : SyntaxNode
{
using var context = await TestContext.CreateAsync(initial, expected);
var declarationNode = context.GetDestinationNode().FirstAncestorOrSelf<T>();
var updatedDeclarationNode = declarationNode;
var workspace = context.Document.Project.Solution.Workspace;
if (accessibility.HasValue)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationAccessibility(declarationNode, workspace, accessibility.Value);
}
else if (modifiers != null)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationModifiers(declarationNode, workspace, modifiers);
}
else if (getType != null)
{
updatedDeclarationNode = CodeGenerator.UpdateDeclarationType(declarationNode, workspace, getType(context.SemanticModel));
}
else if (getNewMembers != null)
{
var retainedMembers = context.GetAnnotatedDeclaredSymbols(retainedMembersKey, context.SemanticModel);
var newMembersToAdd = GetSymbols(getNewMembers, context);
var allMembers = new List<ISymbol>();
if (declareNewMembersAtTop.HasValue && declareNewMembersAtTop.Value)
{
allMembers.AddRange(newMembersToAdd);
allMembers.AddRange(retainedMembers);
}
else
{
allMembers.AddRange(retainedMembers);
allMembers.AddRange(newMembersToAdd);
}
updatedDeclarationNode = CodeGenerator.UpdateDeclarationMembers(declarationNode, workspace, allMembers);
}
updatedDeclarationNode = updatedDeclarationNode.WithAdditionalAnnotations(Formatter.Annotation);
context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, updatedDeclarationNode));
}
internal static async Task TestGenerateFromSourceSymbolAsync(
string symbolSource,
string initial,
string expected,
bool onlyGenerateMembers = false,
CodeGenerationOptions codeGenerationOptions = null,
string forceLanguage = null)
{
using var context = await TestContext.CreateAsync(initial, expected, forceLanguage);
var destSpan = new TextSpan();
MarkupTestFile.GetSpan(symbolSource.NormalizeLineEndings(), out symbolSource, out destSpan);
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
var semanticModel = await context.Solution
.AddProject(projectId, "GenerationSource", "GenerationSource", TestContext.GetLanguage(symbolSource))
.AddDocument(documentId, "Source.cs", symbolSource)
.GetDocument(documentId)
.GetSemanticModelAsync();
var docOptions = await context.Document.GetOptionsAsync();
codeGenerationOptions ??= new CodeGenerationOptions();
codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? docOptions);
var symbol = TestContext.GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, semanticModel);
var destination = context.GetDestination();
if (destination.IsType)
{
var members = onlyGenerateMembers ? symbol.GetMembers().ToArray() : new[] { symbol };
context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)destination, members, codeGenerationOptions);
}
else
{
context.Result = await context.Service.AddNamespaceOrTypeAsync(context.Solution, (INamespaceSymbol)destination, symbol, codeGenerationOptions);
}
}
internal static Func<SemanticModel, IParameterSymbol> Parameter(Type type, string name, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false)
{
return s => CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, type), name,
isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue);
}
internal static Func<SemanticModel, IParameterSymbol> Parameter(string typeFullName, string parameterName, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false, int typeArrayRank = 0)
{
return s => CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, typeFullName, typeArrayRank), parameterName,
isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue);
}
private static ITypeSymbol GetTypeSymbol(Compilation compilation, Type type)
=> !type.IsArray ? GetTypeSymbol(compilation, type.FullName) : GetTypeSymbol(compilation, type.GetElementType().FullName, type.GetArrayRank());
private static ITypeSymbol GetTypeSymbol(Compilation compilation, string typeFullName, int arrayRank = 0)
{
return arrayRank == 0 ? (ITypeSymbol)compilation.GetTypeByMetadataName(typeFullName)
: compilation.CreateArrayTypeSymbol(compilation.GetTypeByMetadataName(typeFullName), arrayRank);
}
internal static ImmutableArray<Func<SemanticModel, IParameterSymbol>> Parameters(params Func<SemanticModel, IParameterSymbol>[] p)
=> p.ToImmutableArray();
internal static ImmutableArray<Func<SemanticModel, ISymbol>> Members(params Func<SemanticModel, ISymbol>[] m)
=> m.ToImmutableArray();
internal static Func<SemanticModel, ITypeSymbol> CreateArrayType(Type type, int rank = 1)
=> s => CodeGenerationSymbolFactory.CreateArrayTypeSymbol(GetTypeSymbol(type)(s), rank);
private static ImmutableArray<IParameterSymbol> GetParameterSymbols(ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, TestContext context)
=> parameters.IsDefault
? default
: parameters.SelectAsArray(p => p(context.SemanticModel));
private static ImmutableArray<IMethodSymbol> GetMethodSymbols(
Func<SemanticModel, ImmutableArray<IMethodSymbol>> explicitInterface, TestContext context)
{
return explicitInterface == null ? default : explicitInterface(context.SemanticModel);
}
private static ImmutableArray<ISymbol> GetSymbols(ImmutableArray<Func<SemanticModel, ISymbol>> members, TestContext context)
{
return members == null
? default
: members.SelectAsArray(m => m(context.SemanticModel));
}
private static Func<SemanticModel, ISymbol> CreateEnumField(string name, object value)
{
return s => CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default, Accessibility.Public,
new Editing.DeclarationModifiers(), GetTypeSymbol(typeof(int))(s), name, value != null, value);
}
internal static Func<SemanticModel, ISymbol> CreateField(Accessibility accessibility, Editing.DeclarationModifiers modifiers, Type type, string name)
{
return s => CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default, accessibility,
modifiers, GetTypeSymbol(type)(s), name);
}
private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(Type type)
=> GetTypeSymbol(type.FullName);
private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(string typeMetadataName)
=> s => s?.Compilation.GetTypeByMetadataName(typeMetadataName);
internal static IEnumerable<SyntaxToken> CreateModifierTokens(Editing.DeclarationModifiers modifiers, string language)
{
if (language == LanguageNames.CSharp)
{
if (modifiers.IsAbstract)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AbstractKeyword);
}
if (modifiers.IsAsync)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AsyncKeyword);
}
if (modifiers.IsConst)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ConstKeyword);
}
if (modifiers.IsNew)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.NewKeyword);
}
if (modifiers.IsOverride)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.OverrideKeyword);
}
if (modifiers.IsPartial)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.PartialKeyword);
}
if (modifiers.IsReadOnly)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ReadOnlyKeyword);
}
if (modifiers.IsSealed)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.SealedKeyword);
}
if (modifiers.IsStatic)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.StaticKeyword);
}
if (modifiers.IsUnsafe)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.UnsafeKeyword);
}
if (modifiers.IsVirtual)
{
yield return CS.SyntaxFactory.Token(CS.SyntaxKind.VirtualKeyword);
}
}
else
{
if (modifiers.IsAbstract)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.MustOverrideKeyword);
}
if (modifiers.IsAsync)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.AsyncKeyword);
}
if (modifiers.IsConst)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ConstKeyword);
}
if (modifiers.IsNew)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NewKeyword);
}
if (modifiers.IsOverride)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridesKeyword);
}
if (modifiers.IsPartial)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.PartialKeyword);
}
if (modifiers.IsReadOnly)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ReadOnlyKeyword);
}
if (modifiers.IsSealed)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NotInheritableKeyword);
}
if (modifiers.IsStatic)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.StaticKeyword);
}
if (modifiers.IsVirtual)
{
yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridableKeyword);
}
}
}
internal class TestContext : IDisposable
{
private readonly string _expected;
public readonly bool IsVisualBasic;
public Document Document;
public SemanticModel SemanticModel;
public SyntaxTree SyntaxTree;
public ICodeGenerationService Service;
public Document Result;
public readonly TestWorkspace Workspace;
private readonly string _language;
private readonly bool _ignoreResult;
public TestContext(
string expected,
bool ignoreResult,
string language,
TestWorkspace workspace,
SemanticModel semanticModel)
{
_expected = expected.NormalizeLineEndings();
_language = language;
this.IsVisualBasic = _language == LanguageNames.VisualBasic;
_ignoreResult = ignoreResult;
Workspace = workspace;
this.Document = Workspace.CurrentSolution.Projects.Single().Documents.Single();
this.SemanticModel = semanticModel;
this.SyntaxTree = SemanticModel.SyntaxTree;
this.Service = Document.Project.LanguageServices.GetService<ICodeGenerationService>();
}
public static async Task<TestContext> CreateAsync(string initial, string expected, string forceLanguage = null, bool ignoreResult = false)
{
var language = forceLanguage ?? GetLanguage(initial);
var isVisualBasic = language == LanguageNames.VisualBasic;
var workspace = CreateWorkspaceFromFile(initial.NormalizeLineEndings(), isVisualBasic, null, null);
var semanticModel = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetSemanticModelAsync();
return new TestContext(expected, ignoreResult, language, workspace, semanticModel);
}
public Solution Solution { get { return Workspace.CurrentSolution; } }
public SyntaxNode GetDestinationNode()
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
return SemanticModel.SyntaxTree.GetRoot().FindNode(destSpan, getInnermostNodeForTie: true);
}
public INamespaceOrTypeSymbol GetDestination()
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
return GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, this.SemanticModel);
}
public IEnumerable<ISymbol> GetAnnotatedDeclaredSymbols(string key, SemanticModel semanticModel)
{
var annotatedSpans = Workspace.Documents.Single().AnnotatedSpans[key];
foreach (var span in annotatedSpans)
{
yield return GetSelectedSymbol<ISymbol>(span, semanticModel);
}
}
public static T GetSelectedSymbol<T>(TextSpan selection, SemanticModel semanticModel)
where T : class, ISymbol
{
var token = semanticModel.SyntaxTree.GetRoot().FindToken(selection.Start);
var symbol = token.Parent.AncestorsAndSelf()
.Select(a => semanticModel.GetDeclaredSymbol(a))
.Where(s => s != null).FirstOrDefault() as T;
return symbol;
}
public T GetSelectedSyntax<T>(bool fullSpanCoverage = false) where T : SyntaxNode
{
var destSpan = Workspace.Documents.Single().SelectedSpans.Single();
var token = SemanticModel.SyntaxTree.GetRoot().FindToken(destSpan.Start);
return token.Parent.AncestorsAndSelf().OfType<T>().FirstOrDefault(t => !fullSpanCoverage || t.Span.End >= destSpan.End);
}
public ImmutableArray<SyntaxNode> ParseStatements(string statements)
{
if (statements == null)
{
return default;
}
using var listDisposer = ArrayBuilder<SyntaxNode>.GetInstance(out var list);
var delimiter = IsVisualBasic ? "\r\n" : ";";
var parts = statements.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (var p in parts)
{
if (IsVisualBasic)
{
list.Add(VB.SyntaxFactory.ParseExecutableStatement(p));
}
else
{
list.Add(CS.SyntaxFactory.ParseStatement(p + delimiter));
}
}
return list.ToImmutable();
}
public void Dispose()
{
try
{
if (!_ignoreResult)
{
this.Document = this.Result;
var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result
.GetSyntaxRootAsync().Result.ToFullString();
Assert.Equal(_expected, actual);
}
}
finally
{
Workspace.Dispose();
}
}
public static string GetLanguage(string input)
{
return ContainsVisualBasicKeywords(input)
? LanguageNames.VisualBasic : LanguageNames.CSharp;
}
private static bool ContainsVisualBasicKeywords(string input)
{
return
input.Contains("Module") ||
input.Contains("Class") ||
input.Contains("Structure") ||
input.Contains("Namespace") ||
input.Contains("Sub") ||
input.Contains("Function") ||
input.Contains("Dim") ||
input.Contains("Enum");
}
private static TestWorkspace CreateWorkspaceFromFile(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions)
{
return isVisualBasic ?
TestWorkspace.CreateVisualBasic(file, (VB.VisualBasicParseOptions)parseOptions, (VB.VisualBasicCompilationOptions)compilationOptions) :
TestWorkspace.CreateCSharp(file, (CS.CSharpParseOptions)parseOptions, (CS.CSharpCompilationOptions)compilationOptions);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/Portable/CodeGen/ITokenDeferral.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeGen
{
internal interface ITokenDeferral
{
uint GetFakeStringTokenForIL(string value);
uint GetFakeSymbolTokenForIL(Cci.IReference value, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
uint GetFakeSymbolTokenForIL(Cci.ISignature value, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document);
Cci.IFieldReference GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
Cci.IMethodReference GetInitArrayHelper();
string GetStringFromToken(uint token);
/// <summary>
/// Gets the <see cref="Cci.IReference"/> or <see cref="Cci.ISignature"/> corresponding to this token.
/// </summary>
object GetReferenceFromToken(uint token);
ArrayMethods ArrayMethods { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CodeGen
{
internal interface ITokenDeferral
{
uint GetFakeStringTokenForIL(string value);
uint GetFakeSymbolTokenForIL(Cci.IReference value, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
uint GetFakeSymbolTokenForIL(Cci.ISignature value, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document);
Cci.IFieldReference GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics);
Cci.IMethodReference GetInitArrayHelper();
string GetStringFromToken(uint token);
/// <summary>
/// Gets the <see cref="Cci.IReference"/> or <see cref="Cci.ISignature"/> corresponding to this token.
/// </summary>
object GetReferenceFromToken(uint token);
ArrayMethods ArrayMethods { get; }
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias InteractiveHost;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostDesktopInitTests : AbstractInteractiveHostTests
{
internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop32;
internal override bool UseDefaultInitializationFile => true;
[Fact]
public async Task SearchPaths1()
{
var fxDir = await GetHostRuntimeDirectoryAsync();
var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01);
var srcDir = Temp.CreateDirectory();
var dllDir = Path.GetDirectoryName(dll.Path)!;
srcDir.CreateFile("goo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");");
// print default:
await Host.ExecuteAsync(@"ReferencePaths");
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir), output);
await Host.ExecuteAsync(@"SourcePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(), output);
// add and test if added:
await Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");");
await Host.ExecuteAsync(@"SourcePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(srcDir.Path), output);
// execute file (uses modified search paths), the file adds a reference path
await Host.ExecuteFileAsync("goo.csx");
await Host.ExecuteAsync(@"ReferencePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir, dllDir), output);
await Host.AddReferenceAsync(Path.GetFileName(dll.Path));
await Host.ExecuteAsync(@"typeof(Metadata.ICSProp)");
var error = await ReadErrorOutputToEnd();
output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("[Metadata.ICSProp]\r\n", output);
}
[Fact]
public async Task AddReference_AssemblyAlreadyLoaded()
{
var result = await LoadReference("System.Core");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", output);
Assert.True(result);
result = await LoadReference("System.Core.dll");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", output);
Assert.True(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.
extern alias InteractiveHost;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostDesktopInitTests : AbstractInteractiveHostTests
{
internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop32;
internal override bool UseDefaultInitializationFile => true;
[Fact]
public async Task SearchPaths1()
{
var fxDir = await GetHostRuntimeDirectoryAsync();
var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01);
var srcDir = Temp.CreateDirectory();
var dllDir = Path.GetDirectoryName(dll.Path)!;
srcDir.CreateFile("goo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");");
// print default:
await Host.ExecuteAsync(@"ReferencePaths");
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir), output);
await Host.ExecuteAsync(@"SourcePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(), output);
// add and test if added:
await Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");");
await Host.ExecuteAsync(@"SourcePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(srcDir.Path), output);
// execute file (uses modified search paths), the file adds a reference path
await Host.ExecuteFileAsync("goo.csx");
await Host.ExecuteAsync(@"ReferencePaths");
output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir, dllDir), output);
await Host.AddReferenceAsync(Path.GetFileName(dll.Path));
await Host.ExecuteAsync(@"typeof(Metadata.ICSProp)");
var error = await ReadErrorOutputToEnd();
output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("[Metadata.ICSProp]\r\n", output);
}
[Fact]
public async Task AddReference_AssemblyAlreadyLoaded()
{
var result = await LoadReference("System.Core");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", output);
Assert.True(result);
result = await LoadReference("System.Core.dll");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", output);
Assert.True(result);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/IfKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public IfKeywordRecommender()
: base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsPreProcessorKeywordContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public IfKeywordRecommender()
: base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsPreProcessorKeywordContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core/Extensibility/Highlighting/ExportHighlighterAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Editor
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
[ExcludeFromCodeCoverage]
internal class ExportHighlighterAttribute : ExportAttribute
{
public string Language { get; }
public ExportHighlighterAttribute(string language)
: base(typeof(IHighlighter))
{
this.Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Editor
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
[ExcludeFromCodeCoverage]
internal class ExportHighlighterAttribute : ExportAttribute
{
public string Language { get; }
public ExportHighlighterAttribute(string language)
: base(typeof(IHighlighter))
{
this.Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
using MetadataOrDiagnostic = System.Object;
/// <summary>
/// The base class for language specific assembly managers.
/// </summary>
/// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam>
/// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam>
internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
where TCompilation : Compilation
where TAssemblySymbol : class, IAssemblySymbolInternal
{
protected abstract CommonMessageProvider MessageProvider { get; }
protected abstract AssemblyData CreateAssemblyDataForFile(
PEAssembly assembly,
WeakList<IAssemblySymbolInternal> cachedSymbols,
DocumentationProvider documentationProvider,
string sourceAssemblySimpleName,
MetadataImportOptions importOptions,
bool embedInteropTypes);
protected abstract AssemblyData CreateAssemblyDataForCompilation(
CompilationReference compilationReference);
/// <summary>
/// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>.
/// Reports inconsistencies to the given diagnostic bag.
/// </summary>
/// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns>
protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics);
/// <summary>
/// Called to compare two weakly named identities with the same name.
/// </summary>
protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2);
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
protected struct ResolvedReference
{
private readonly MetadataImageKind _kind;
private readonly int _index;
private readonly ImmutableArray<string> _aliasesOpt;
private readonly ImmutableArray<string> _recursiveAliasesOpt;
private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt;
// uninitialized aliases
public ResolvedReference(int index, MetadataImageKind kind)
{
Debug.Assert(index >= 0);
_index = index + 1;
_kind = kind;
_aliasesOpt = default(ImmutableArray<string>);
_recursiveAliasesOpt = default(ImmutableArray<string>);
_mergedReferencesOpt = default(ImmutableArray<MetadataReference>);
}
// initialized aliases
public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences)
: this(index, kind)
{
// We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged.
Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault);
Debug.Assert(!mergedReferences.IsDefault);
_aliasesOpt = aliasesOpt;
_recursiveAliasesOpt = recursiveAliasesOpt;
_mergedReferencesOpt = mergedReferences;
}
private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault;
/// <summary>
/// Aliases that should be applied to the referenced assembly.
/// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
/// Null if not applicable (the reference only has recursive aliases).
/// </summary>
public ImmutableArray<string> AliasesOpt
{
get
{
Debug.Assert(!IsUninitialized);
return _aliasesOpt;
}
}
/// <summary>
/// Aliases that should be applied recursively to all dependent assemblies.
/// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
/// Null if not applicable (the reference only has simple aliases).
/// </summary>
public ImmutableArray<string> RecursiveAliasesOpt
{
get
{
Debug.Assert(!IsUninitialized);
return _recursiveAliasesOpt;
}
}
public ImmutableArray<MetadataReference> MergedReferences
{
get
{
Debug.Assert(!IsUninitialized);
return _mergedReferencesOpt;
}
}
/// <summary>
/// default(<see cref="ResolvedReference"/>) is considered skipped.
/// </summary>
public bool IsSkipped
{
get
{
return _index == 0;
}
}
public MetadataImageKind Kind
{
get
{
Debug.Assert(!IsSkipped);
return _kind;
}
}
/// <summary>
/// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>.
/// </summary>
public int Index
{
get
{
Debug.Assert(!IsSkipped);
return _index - 1;
}
}
private string GetDebuggerDisplay()
{
return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}";
}
private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name)
{
return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'";
}
}
protected readonly struct ReferencedAssemblyIdentity
{
public readonly AssemblyIdentity? Identity;
public readonly MetadataReference? Reference;
/// <summary>
/// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies.
/// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies.
/// </summary>
public readonly int RelativeAssemblyIndex;
public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) =>
RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex;
public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex)
{
Identity = identity;
Reference = reference;
RelativeAssemblyIndex = relativeAssemblyIndex;
}
}
/// <summary>
/// Resolves given metadata references to assemblies and modules.
/// </summary>
/// <param name="compilation">The compilation whose references are being resolved.</param>
/// <param name="assemblyReferencesBySimpleName">
/// Used to filter out assemblies that have the same strong or weak identity.
/// Maps simple name to a list of identities. The highest version of each name is the first.
/// </param>
/// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param>
/// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param>
/// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param>
/// <param name="assemblies">List where to store information about resolved assemblies to.</param>
/// <param name="modules">List where to store information about resolved modules to.</param>
/// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param>
/// <returns>
/// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively.
///</returns>
protected ImmutableArray<ResolvedReference> ResolveMetadataReferences(
TCompilation compilation,
[Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<MetadataReference> references,
out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap,
out ImmutableArray<MetadataReference> boundReferenceDirectives,
out ImmutableArray<AssemblyData> assemblies,
out ImmutableArray<PEModule> modules,
DiagnosticBag diagnostics)
{
// Locations of all #r directives in the order they are listed in the references list.
ImmutableArray<Location> referenceDirectiveLocations;
GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations);
// References originating from #r directives precede references supplied as arguments of the compilation.
int referenceCount = references.Length;
int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0);
var referenceMap = new ResolvedReference[referenceCount];
// Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that
// can be used to alias these references. Duplicate assemblies contribute their aliases into this set.
Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null;
// Used to filter out duplicate references that reference the same file (resolve to the same full normalized path).
var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance);
ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null;
var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance();
ArrayBuilder<PEModule>? lazyModulesBuilder = null;
bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions;
// When duplicate references with conflicting EmbedInteropTypes flag are encountered,
// VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order
// so that we find the one that matters first.
for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--)
{
var boundReference = references[referenceIndex];
if (boundReference == null)
{
continue;
}
// add bound reference if it doesn't exist yet, merging aliases:
MetadataReference? existingReference;
if (boundReferences.TryGetValue(boundReference, out existingReference))
{
// merge properties of compilation-based references if the underlying compilations are the same
if ((object)boundReference != existingReference)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
}
continue;
}
boundReferences.Add(boundReference, boundReference);
Location location;
if (referenceIndex < referenceDirectiveCount)
{
location = referenceDirectiveLocations[referenceIndex];
uniqueDirectiveReferences!.Add(boundReference);
}
else
{
location = Location.None;
}
// compilation reference
var compilationReference = boundReference as CompilationReference;
if (compilationReference != null)
{
switch (compilationReference.Properties.Kind)
{
case MetadataImageKind.Assembly:
existingReference = TryAddAssembly(
compilationReference.Compilation.Assembly.Identity,
boundReference,
-assembliesBuilder.Count - 1,
diagnostics,
location,
assemblyReferencesBySimpleName,
supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
continue;
}
// Note, if SourceAssemblySymbol hasn't been created for
// compilationAssembly.Compilation yet, we want this to happen
// right now. Conveniently, this constructor will trigger creation of the
// SourceAssemblySymbol.
var asmData = CreateAssemblyDataForCompilation(compilationReference);
AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
break;
default:
throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind);
}
continue;
}
// PE reference
var peReference = (PortableExecutableReference)boundReference;
Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics);
Debug.Assert(metadata != null || diagnostics.HasAnyErrors());
if (metadata != null)
{
switch (peReference.Properties.Kind)
{
case MetadataImageKind.Assembly:
var assemblyMetadata = (AssemblyMetadata)metadata;
WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols;
if (assemblyMetadata.IsValidAssembly())
{
PEAssembly? assembly = assemblyMetadata.GetAssembly();
Debug.Assert(assembly is object);
existingReference = TryAddAssembly(
assembly.Identity,
peReference,
-assembliesBuilder.Count - 1,
diagnostics,
location,
assemblyReferencesBySimpleName,
supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
continue;
}
var asmData = CreateAssemblyDataForFile(
assembly,
cachedSymbols,
peReference.DocumentationProvider,
SimpleAssemblyName,
compilation.Options.MetadataImportOptions,
peReference.Properties.EmbedInteropTypes);
AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
}
else
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? ""));
}
// asmData keeps strong ref after this point
GC.KeepAlive(assemblyMetadata);
break;
case MetadataImageKind.Module:
var moduleMetadata = (ModuleMetadata)metadata;
if (moduleMetadata.Module.IsLinkedModule)
{
// We don't support netmodules since some checks in the compiler need information from the full PE image
// (Machine, Bit32Required, PE image hash).
if (!moduleMetadata.Module.IsEntireImageAvailable)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? ""));
}
AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder);
}
else
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? ""));
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind);
}
}
}
if (uniqueDirectiveReferences != null)
{
uniqueDirectiveReferences.ReverseContents();
boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree();
}
else
{
boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty;
}
// We enumerated references in reverse order in the above code
// and thus assemblies and modules in the builders are reversed.
// Fix up all the indices and reverse the builder content now to get
// the ordering matching the references.
//
// Also fills in aliases.
for (int i = 0; i < referenceMap.Length; i++)
{
if (!referenceMap[i].IsSkipped)
{
int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0;
int reversedIndex = count - 1 - referenceMap[i].Index;
referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap);
}
}
assembliesBuilder.ReverseContents();
assemblies = assembliesBuilder.ToImmutableAndFree();
if (lazyModulesBuilder == null)
{
modules = ImmutableArray<PEModule>.Empty;
}
else
{
lazyModulesBuilder.ReverseContents();
modules = lazyModulesBuilder.ToImmutableAndFree();
}
return ImmutableArray.CreateRange(referenceMap);
}
private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt)
{
ImmutableArray<string> aliasesOpt, recursiveAliasesOpt;
var mergedReferences = ImmutableArray<MetadataReference>.Empty;
if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties))
{
aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
if (mergedProperties.MergedReferencesOpt is object)
{
mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree();
}
}
else if (reference.Properties.HasRecursiveAliases)
{
aliasesOpt = default(ImmutableArray<string>);
recursiveAliasesOpt = reference.Properties.Aliases;
}
else
{
aliasesOpt = reference.Properties.Aliases;
recursiveAliasesOpt = default(ImmutableArray<string>);
}
return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences);
}
/// <summary>
/// Creates or gets metadata for PE reference.
/// </summary>
/// <remarks>
/// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>,
/// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>.
/// </remarks>
private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics)
{
Metadata? existingMetadata;
lock (ObservedMetadata)
{
if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
{
return existingMetadata;
}
}
Metadata? newMetadata;
Diagnostic? newDiagnostic = null;
try
{
newMetadata = peReference.GetMetadataNoCopy();
// make sure basic structure of the PE image is valid:
if (newMetadata is AssemblyMetadata assemblyMetadata)
{
_ = assemblyMetadata.IsValidAssembly();
}
else
{
_ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule;
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind);
newMetadata = null;
}
lock (ObservedMetadata)
{
if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
{
return existingMetadata;
}
if (newDiagnostic != null)
{
diagnostics.Add(newDiagnostic);
}
ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!);
return newMetadata;
}
}
private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata)
{
if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing))
{
Debug.Assert(existing is Metadata || existing is Diagnostic);
metadata = existing as Metadata;
if (metadata == null)
{
diagnostics.Add((Diagnostic)existing);
}
return true;
}
metadata = null;
return false;
}
internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics)
{
var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics);
Debug.Assert(metadata != null || diagnostics.HasAnyErrors());
if (metadata == null)
{
return null;
}
// require the metadata to be a valid assembly metadata:
var assemblyMetadata = metadata as AssemblyMetadata;
if (assemblyMetadata?.IsValidAssembly() != true)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? ""));
return null;
}
return assemblyMetadata;
}
/// <summary>
/// Determines whether references are the same. Compilation references are the same if they refer to the same compilation.
/// Otherwise, references are represented by their object identities.
/// </summary>
internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference>
{
internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer();
public bool Equals(MetadataReference? x, MetadataReference? y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var cx = x as CompilationReference;
if (cx != null)
{
var cy = y as CompilationReference;
if (cy != null)
{
return (object)cx.Compilation == cy.Compilation;
}
}
return false;
}
public int GetHashCode(MetadataReference reference)
{
var compilationReference = reference as CompilationReference;
if (compilationReference != null)
{
return RuntimeHelpers.GetHashCode(compilationReference.Compilation);
}
return RuntimeHelpers.GetHashCode(reference);
}
}
/// <summary>
/// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>).
/// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols.
/// </summary>
private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap)
{
if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics))
{
return;
}
if (lazyAliasMap == null)
{
lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>();
}
MergedAliases? mergedAliases;
if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases))
{
mergedAliases = new MergedAliases();
lazyAliasMap.Add(primaryReference, mergedAliases);
mergedAliases.Merge(primaryReference);
}
mergedAliases.Merge(newReference);
}
/// <remarks>
/// Caller is responsible for freeing any allocated ArrayBuilders.
/// </remarks>
private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies)
{
// aliases will be filled in later:
referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly);
assemblies.Add(data);
}
/// <remarks>
/// Caller is responsible for freeing any allocated ArrayBuilders.
/// </remarks>
private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules)
{
if (modules == null)
{
modules = ArrayBuilder<PEModule>.GetInstance();
}
referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module);
modules.Add(module);
}
/// <summary>
/// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it.
/// Two identities are considered equivalent if
/// - both assembly names are strong (have keys) and are either equal or FX unified
/// - both assembly names are weak (no keys) and have the same simple name.
/// </summary>
private MetadataReference? TryAddAssembly(
AssemblyIdentity identity,
MetadataReference reference,
int assemblyIndex,
DiagnosticBag diagnostics,
Location location,
Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName,
bool supersedeLowerVersions)
{
var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex);
List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities;
if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
{
referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly });
return null;
}
if (supersedeLowerVersions)
{
foreach (var other in sameSimpleNameIdentities)
{
Debug.Assert(other.Identity is object);
if (identity.Version == other.Identity.Version)
{
return other.Reference;
}
}
// Keep all versions of the assembly and the first identity in the list the one with the highest version:
if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version)
{
sameSimpleNameIdentities.Add(referencedAssembly);
}
else
{
sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]);
sameSimpleNameIdentities[0] = referencedAssembly;
}
return null;
}
ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity);
if (identity.IsStrongName)
{
foreach (var other in sameSimpleNameIdentities)
{
// Only compare strong with strong (weak is never equivalent to strong and vice versa).
// In order to eliminate duplicate references we need to try to match their identities in both directions since
// ReferenceMatchesDefinition is not necessarily symmetric.
// (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.)
Debug.Assert(other.Identity is object);
if (other.Identity.IsStrongName &&
IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) &&
IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity))
{
equivalent = other;
break;
}
}
}
else
{
foreach (var other in sameSimpleNameIdentities)
{
// only compare weak with weak
Debug.Assert(other.Identity is object);
if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity))
{
equivalent = other;
break;
}
}
}
if (equivalent.Identity == null)
{
sameSimpleNameIdentities.Add(referencedAssembly);
return null;
}
// equivalent found - ignore and/or report an error:
if (identity.IsStrongName)
{
Debug.Assert(equivalent.Identity.IsStrongName);
// versions might have been unified for a Framework assembly:
if (identity != equivalent.Identity)
{
// Dev12 C# reports an error
// Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used.
// BREAKING CHANGE in VB: we report an error for both languages
// Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.
MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity);
}
// If the versions match exactly we ignore duplicates w/o reporting errors while
// Dev12 C# reports:
// error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references.
// Dev12 VB reports:
// Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System.
// A second reference to 'D:\Temp\System.dll' cannot be added.
}
else
{
Debug.Assert(!equivalent.Identity.IsStrongName);
// Dev12 reports an error for all weak-named assemblies, even if the versions are the same.
// We treat assemblies with the same name and version equal even if they don't have a strong name.
// This change allows us to de-duplicate #r references based on identities rather than full paths,
// and is closer to platforms that don't support strong names and consider name and version enough
// to identify an assembly. An identity without version is considered to have version 0.0.0.0.
if (identity != equivalent.Identity)
{
MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity);
}
}
Debug.Assert(equivalent.Reference != null);
return equivalent.Reference;
}
protected void GetCompilationReferences(
TCompilation compilation,
DiagnosticBag diagnostics,
out ImmutableArray<MetadataReference> references,
out IDictionary<(string, string), MetadataReference> boundReferenceDirectives,
out ImmutableArray<Location> referenceDirectiveLocations)
{
ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance();
ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null;
IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null;
try
{
foreach (var referenceDirective in compilation.ReferenceDirectives)
{
Debug.Assert(referenceDirective.Location is object);
if (compilation.Options.MetadataReferenceResolver == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location));
break;
}
// we already successfully bound #r with the same value:
Debug.Assert(referenceDirective.File is object);
Debug.Assert(referenceDirective.Location.SourceTree is object);
if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File)))
{
continue;
}
MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation);
if (boundReference == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File));
continue;
}
if (localBoundReferenceDirectives == null)
{
localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>();
referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance();
}
referencesBuilder.Add(boundReference);
referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location);
localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference);
}
// add external reference at the end, so that they are processed first:
referencesBuilder.AddRange(compilation.ExternalReferences);
// Add all explicit references of the previous script compilation.
var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation;
if (previousScriptCompilation != null)
{
referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences);
}
if (localBoundReferenceDirectives == null)
{
// no directive references resolved successfully:
localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>();
}
boundReferenceDirectives = localBoundReferenceDirectives;
references = referencesBuilder.ToImmutable();
referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty;
}
finally
{
// Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and
// we don't want to clutter the test output with leak reports.
referencesBuilder.Free();
}
}
/// <summary>
/// For each given directive return a bound PE reference, or null if the binding fails.
/// </summary>
private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation)
{
var tree = location.SourceTree;
string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null;
// checked earlier:
Debug.Assert(compilation.Options.MetadataReferenceResolver != null);
var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true));
if (references.IsDefaultOrEmpty)
{
return null;
}
if (references.Length > 1)
{
// TODO: implement
throw new NotSupportedException();
}
return references[0];
}
internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies(
ImmutableArray<AssemblyIdentity> references,
ImmutableArray<AssemblyData> definitions,
int definitionStartIndex,
AssemblyIdentityComparer assemblyIdentityComparer)
{
var boundReferences = new AssemblyReferenceBinding[references.Length];
for (int j = 0; j < references.Length; j++)
{
boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer);
}
return boundReferences;
}
/// <summary>
/// Used to match AssemblyRef with AssemblyDef.
/// </summary>
/// <param name="definitions">Array of definition identities to match against.</param>
/// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param>
/// <param name="reference">Reference identity to resolve.</param>
/// <param name="assemblyIdentityComparer">Assembly identity comparer.</param>
/// <returns>
/// Returns an index the reference is bound.
/// </returns>
internal static AssemblyReferenceBinding ResolveReferencedAssembly(
AssemblyIdentity reference,
ImmutableArray<AssemblyData> definitions,
int definitionStartIndex,
AssemblyIdentityComparer assemblyIdentityComparer)
{
// Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version.
// For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version.
// If match.Version != reference.Version a warning is reported.
// definition with the lowest version higher than reference version, unless exact version found
int minHigherVersionDefinition = -1;
int maxLowerVersionDefinition = -1;
// Skip assembly being built for now; it will be considered at the very end:
bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0;
definitionStartIndex = Math.Max(definitionStartIndex, 1);
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
AssemblyIdentity definition = definitions[i].Identity;
switch (assemblyIdentityComparer.Compare(reference, definition))
{
case AssemblyIdentityComparer.ComparisonResult.NotEquivalent:
continue;
case AssemblyIdentityComparer.ComparisonResult.Equivalent:
return new AssemblyReferenceBinding(reference, i);
case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion:
if (reference.Version < definition.Version)
{
// Refers to an older assembly than we have
if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version)
{
minHigherVersionDefinition = i;
}
}
else
{
Debug.Assert(reference.Version > definition.Version);
// Refers to a newer assembly than we have
if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version)
{
maxLowerVersionDefinition = i;
}
}
continue;
default:
throw ExceptionUtilities.Unreachable;
}
}
// we haven't found definition that matches the reference
if (minHigherVersionDefinition != -1)
{
return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1);
}
if (maxLowerVersionDefinition != -1)
{
return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1);
}
// Handle cases where Windows.winmd is a runtime substitute for a
// reference to a compile-time winmd. This is for scenarios such as a
// debugger EE which constructs a compilation from the modules of
// the running process where Windows.winmd loaded at runtime is a
// substitute for a collection of Windows.*.winmd compile-time references.
if (reference.IsWindowsComponent())
{
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
if (definitions[i].Identity.IsWindowsRuntime())
{
return new AssemblyReferenceBinding(reference, i);
}
}
}
// In the IDE it is possible the reference we're looking for is a
// compilation reference to a source assembly. However, if the reference
// is of ContentType WindowsRuntime then the compilation will never
// match since all C#/VB WindowsRuntime compilations output .winmdobjs,
// not .winmds, and the ContentType of a .winmdobj is Default.
// If this is the case, we want to ignore the ContentType mismatch and
// allow the compilation to match the reference.
if (reference.ContentType == AssemblyContentType.WindowsRuntime)
{
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
var definition = definitions[i].Identity;
var sourceCompilation = definitions[i].SourceCompilation;
if (definition.ContentType == AssemblyContentType.Default &&
sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata &&
AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) &&
reference.Version.Equals(definition.Version) &&
reference.IsRetargetable == definition.IsRetargetable &&
AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) &&
AssemblyIdentity.KeysEqual(reference, definition))
{
return new AssemblyReferenceBinding(reference, i);
}
}
}
// As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the
// compilation (i.e. source) assembly as a last resort. We follow the native approach of
// skipping the public key comparison since we have yet to compute it.
if (resolveAgainstAssemblyBeingBuilt &&
AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name))
{
Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty);
return new AssemblyReferenceBinding(reference, 0);
}
return new AssemblyReferenceBinding(reference);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
using MetadataOrDiagnostic = System.Object;
/// <summary>
/// The base class for language specific assembly managers.
/// </summary>
/// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam>
/// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam>
internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
where TCompilation : Compilation
where TAssemblySymbol : class, IAssemblySymbolInternal
{
protected abstract CommonMessageProvider MessageProvider { get; }
protected abstract AssemblyData CreateAssemblyDataForFile(
PEAssembly assembly,
WeakList<IAssemblySymbolInternal> cachedSymbols,
DocumentationProvider documentationProvider,
string sourceAssemblySimpleName,
MetadataImportOptions importOptions,
bool embedInteropTypes);
protected abstract AssemblyData CreateAssemblyDataForCompilation(
CompilationReference compilationReference);
/// <summary>
/// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>.
/// Reports inconsistencies to the given diagnostic bag.
/// </summary>
/// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns>
protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics);
/// <summary>
/// Called to compare two weakly named identities with the same name.
/// </summary>
protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2);
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
protected struct ResolvedReference
{
private readonly MetadataImageKind _kind;
private readonly int _index;
private readonly ImmutableArray<string> _aliasesOpt;
private readonly ImmutableArray<string> _recursiveAliasesOpt;
private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt;
// uninitialized aliases
public ResolvedReference(int index, MetadataImageKind kind)
{
Debug.Assert(index >= 0);
_index = index + 1;
_kind = kind;
_aliasesOpt = default(ImmutableArray<string>);
_recursiveAliasesOpt = default(ImmutableArray<string>);
_mergedReferencesOpt = default(ImmutableArray<MetadataReference>);
}
// initialized aliases
public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences)
: this(index, kind)
{
// We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged.
Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault);
Debug.Assert(!mergedReferences.IsDefault);
_aliasesOpt = aliasesOpt;
_recursiveAliasesOpt = recursiveAliasesOpt;
_mergedReferencesOpt = mergedReferences;
}
private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault;
/// <summary>
/// Aliases that should be applied to the referenced assembly.
/// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
/// Null if not applicable (the reference only has recursive aliases).
/// </summary>
public ImmutableArray<string> AliasesOpt
{
get
{
Debug.Assert(!IsUninitialized);
return _aliasesOpt;
}
}
/// <summary>
/// Aliases that should be applied recursively to all dependent assemblies.
/// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
/// Null if not applicable (the reference only has simple aliases).
/// </summary>
public ImmutableArray<string> RecursiveAliasesOpt
{
get
{
Debug.Assert(!IsUninitialized);
return _recursiveAliasesOpt;
}
}
public ImmutableArray<MetadataReference> MergedReferences
{
get
{
Debug.Assert(!IsUninitialized);
return _mergedReferencesOpt;
}
}
/// <summary>
/// default(<see cref="ResolvedReference"/>) is considered skipped.
/// </summary>
public bool IsSkipped
{
get
{
return _index == 0;
}
}
public MetadataImageKind Kind
{
get
{
Debug.Assert(!IsSkipped);
return _kind;
}
}
/// <summary>
/// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>.
/// </summary>
public int Index
{
get
{
Debug.Assert(!IsSkipped);
return _index - 1;
}
}
private string GetDebuggerDisplay()
{
return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}";
}
private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name)
{
return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'";
}
}
protected readonly struct ReferencedAssemblyIdentity
{
public readonly AssemblyIdentity? Identity;
public readonly MetadataReference? Reference;
/// <summary>
/// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies.
/// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies.
/// </summary>
public readonly int RelativeAssemblyIndex;
public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) =>
RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex;
public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex)
{
Identity = identity;
Reference = reference;
RelativeAssemblyIndex = relativeAssemblyIndex;
}
}
/// <summary>
/// Resolves given metadata references to assemblies and modules.
/// </summary>
/// <param name="compilation">The compilation whose references are being resolved.</param>
/// <param name="assemblyReferencesBySimpleName">
/// Used to filter out assemblies that have the same strong or weak identity.
/// Maps simple name to a list of identities. The highest version of each name is the first.
/// </param>
/// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param>
/// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param>
/// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param>
/// <param name="assemblies">List where to store information about resolved assemblies to.</param>
/// <param name="modules">List where to store information about resolved modules to.</param>
/// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param>
/// <returns>
/// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively.
///</returns>
protected ImmutableArray<ResolvedReference> ResolveMetadataReferences(
TCompilation compilation,
[Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
out ImmutableArray<MetadataReference> references,
out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap,
out ImmutableArray<MetadataReference> boundReferenceDirectives,
out ImmutableArray<AssemblyData> assemblies,
out ImmutableArray<PEModule> modules,
DiagnosticBag diagnostics)
{
// Locations of all #r directives in the order they are listed in the references list.
ImmutableArray<Location> referenceDirectiveLocations;
GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations);
// References originating from #r directives precede references supplied as arguments of the compilation.
int referenceCount = references.Length;
int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0);
var referenceMap = new ResolvedReference[referenceCount];
// Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that
// can be used to alias these references. Duplicate assemblies contribute their aliases into this set.
Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null;
// Used to filter out duplicate references that reference the same file (resolve to the same full normalized path).
var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance);
ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null;
var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance();
ArrayBuilder<PEModule>? lazyModulesBuilder = null;
bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions;
// When duplicate references with conflicting EmbedInteropTypes flag are encountered,
// VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order
// so that we find the one that matters first.
for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--)
{
var boundReference = references[referenceIndex];
if (boundReference == null)
{
continue;
}
// add bound reference if it doesn't exist yet, merging aliases:
MetadataReference? existingReference;
if (boundReferences.TryGetValue(boundReference, out existingReference))
{
// merge properties of compilation-based references if the underlying compilations are the same
if ((object)boundReference != existingReference)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
}
continue;
}
boundReferences.Add(boundReference, boundReference);
Location location;
if (referenceIndex < referenceDirectiveCount)
{
location = referenceDirectiveLocations[referenceIndex];
uniqueDirectiveReferences!.Add(boundReference);
}
else
{
location = Location.None;
}
// compilation reference
var compilationReference = boundReference as CompilationReference;
if (compilationReference != null)
{
switch (compilationReference.Properties.Kind)
{
case MetadataImageKind.Assembly:
existingReference = TryAddAssembly(
compilationReference.Compilation.Assembly.Identity,
boundReference,
-assembliesBuilder.Count - 1,
diagnostics,
location,
assemblyReferencesBySimpleName,
supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
continue;
}
// Note, if SourceAssemblySymbol hasn't been created for
// compilationAssembly.Compilation yet, we want this to happen
// right now. Conveniently, this constructor will trigger creation of the
// SourceAssemblySymbol.
var asmData = CreateAssemblyDataForCompilation(compilationReference);
AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
break;
default:
throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind);
}
continue;
}
// PE reference
var peReference = (PortableExecutableReference)boundReference;
Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics);
Debug.Assert(metadata != null || diagnostics.HasAnyErrors());
if (metadata != null)
{
switch (peReference.Properties.Kind)
{
case MetadataImageKind.Assembly:
var assemblyMetadata = (AssemblyMetadata)metadata;
WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols;
if (assemblyMetadata.IsValidAssembly())
{
PEAssembly? assembly = assemblyMetadata.GetAssembly();
Debug.Assert(assembly is object);
existingReference = TryAddAssembly(
assembly.Identity,
peReference,
-assembliesBuilder.Count - 1,
diagnostics,
location,
assemblyReferencesBySimpleName,
supersedeLowerVersions);
if (existingReference != null)
{
MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
continue;
}
var asmData = CreateAssemblyDataForFile(
assembly,
cachedSymbols,
peReference.DocumentationProvider,
SimpleAssemblyName,
compilation.Options.MetadataImportOptions,
peReference.Properties.EmbedInteropTypes);
AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
}
else
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? ""));
}
// asmData keeps strong ref after this point
GC.KeepAlive(assemblyMetadata);
break;
case MetadataImageKind.Module:
var moduleMetadata = (ModuleMetadata)metadata;
if (moduleMetadata.Module.IsLinkedModule)
{
// We don't support netmodules since some checks in the compiler need information from the full PE image
// (Machine, Bit32Required, PE image hash).
if (!moduleMetadata.Module.IsEntireImageAvailable)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? ""));
}
AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder);
}
else
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? ""));
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind);
}
}
}
if (uniqueDirectiveReferences != null)
{
uniqueDirectiveReferences.ReverseContents();
boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree();
}
else
{
boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty;
}
// We enumerated references in reverse order in the above code
// and thus assemblies and modules in the builders are reversed.
// Fix up all the indices and reverse the builder content now to get
// the ordering matching the references.
//
// Also fills in aliases.
for (int i = 0; i < referenceMap.Length; i++)
{
if (!referenceMap[i].IsSkipped)
{
int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0;
int reversedIndex = count - 1 - referenceMap[i].Index;
referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap);
}
}
assembliesBuilder.ReverseContents();
assemblies = assembliesBuilder.ToImmutableAndFree();
if (lazyModulesBuilder == null)
{
modules = ImmutableArray<PEModule>.Empty;
}
else
{
lazyModulesBuilder.ReverseContents();
modules = lazyModulesBuilder.ToImmutableAndFree();
}
return ImmutableArray.CreateRange(referenceMap);
}
private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt)
{
ImmutableArray<string> aliasesOpt, recursiveAliasesOpt;
var mergedReferences = ImmutableArray<MetadataReference>.Empty;
if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties))
{
aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
if (mergedProperties.MergedReferencesOpt is object)
{
mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree();
}
}
else if (reference.Properties.HasRecursiveAliases)
{
aliasesOpt = default(ImmutableArray<string>);
recursiveAliasesOpt = reference.Properties.Aliases;
}
else
{
aliasesOpt = reference.Properties.Aliases;
recursiveAliasesOpt = default(ImmutableArray<string>);
}
return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences);
}
/// <summary>
/// Creates or gets metadata for PE reference.
/// </summary>
/// <remarks>
/// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>,
/// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>.
/// </remarks>
private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics)
{
Metadata? existingMetadata;
lock (ObservedMetadata)
{
if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
{
return existingMetadata;
}
}
Metadata? newMetadata;
Diagnostic? newDiagnostic = null;
try
{
newMetadata = peReference.GetMetadataNoCopy();
// make sure basic structure of the PE image is valid:
if (newMetadata is AssemblyMetadata assemblyMetadata)
{
_ = assemblyMetadata.IsValidAssembly();
}
else
{
_ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule;
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind);
newMetadata = null;
}
lock (ObservedMetadata)
{
if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
{
return existingMetadata;
}
if (newDiagnostic != null)
{
diagnostics.Add(newDiagnostic);
}
ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!);
return newMetadata;
}
}
private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata)
{
if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing))
{
Debug.Assert(existing is Metadata || existing is Diagnostic);
metadata = existing as Metadata;
if (metadata == null)
{
diagnostics.Add((Diagnostic)existing);
}
return true;
}
metadata = null;
return false;
}
internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics)
{
var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics);
Debug.Assert(metadata != null || diagnostics.HasAnyErrors());
if (metadata == null)
{
return null;
}
// require the metadata to be a valid assembly metadata:
var assemblyMetadata = metadata as AssemblyMetadata;
if (assemblyMetadata?.IsValidAssembly() != true)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? ""));
return null;
}
return assemblyMetadata;
}
/// <summary>
/// Determines whether references are the same. Compilation references are the same if they refer to the same compilation.
/// Otherwise, references are represented by their object identities.
/// </summary>
internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference>
{
internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer();
public bool Equals(MetadataReference? x, MetadataReference? y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var cx = x as CompilationReference;
if (cx != null)
{
var cy = y as CompilationReference;
if (cy != null)
{
return (object)cx.Compilation == cy.Compilation;
}
}
return false;
}
public int GetHashCode(MetadataReference reference)
{
var compilationReference = reference as CompilationReference;
if (compilationReference != null)
{
return RuntimeHelpers.GetHashCode(compilationReference.Compilation);
}
return RuntimeHelpers.GetHashCode(reference);
}
}
/// <summary>
/// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>).
/// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols.
/// </summary>
private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap)
{
if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics))
{
return;
}
if (lazyAliasMap == null)
{
lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>();
}
MergedAliases? mergedAliases;
if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases))
{
mergedAliases = new MergedAliases();
lazyAliasMap.Add(primaryReference, mergedAliases);
mergedAliases.Merge(primaryReference);
}
mergedAliases.Merge(newReference);
}
/// <remarks>
/// Caller is responsible for freeing any allocated ArrayBuilders.
/// </remarks>
private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies)
{
// aliases will be filled in later:
referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly);
assemblies.Add(data);
}
/// <remarks>
/// Caller is responsible for freeing any allocated ArrayBuilders.
/// </remarks>
private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules)
{
if (modules == null)
{
modules = ArrayBuilder<PEModule>.GetInstance();
}
referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module);
modules.Add(module);
}
/// <summary>
/// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it.
/// Two identities are considered equivalent if
/// - both assembly names are strong (have keys) and are either equal or FX unified
/// - both assembly names are weak (no keys) and have the same simple name.
/// </summary>
private MetadataReference? TryAddAssembly(
AssemblyIdentity identity,
MetadataReference reference,
int assemblyIndex,
DiagnosticBag diagnostics,
Location location,
Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName,
bool supersedeLowerVersions)
{
var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex);
List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities;
if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
{
referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly });
return null;
}
if (supersedeLowerVersions)
{
foreach (var other in sameSimpleNameIdentities)
{
Debug.Assert(other.Identity is object);
if (identity.Version == other.Identity.Version)
{
return other.Reference;
}
}
// Keep all versions of the assembly and the first identity in the list the one with the highest version:
if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version)
{
sameSimpleNameIdentities.Add(referencedAssembly);
}
else
{
sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]);
sameSimpleNameIdentities[0] = referencedAssembly;
}
return null;
}
ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity);
if (identity.IsStrongName)
{
foreach (var other in sameSimpleNameIdentities)
{
// Only compare strong with strong (weak is never equivalent to strong and vice versa).
// In order to eliminate duplicate references we need to try to match their identities in both directions since
// ReferenceMatchesDefinition is not necessarily symmetric.
// (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.)
Debug.Assert(other.Identity is object);
if (other.Identity.IsStrongName &&
IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) &&
IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity))
{
equivalent = other;
break;
}
}
}
else
{
foreach (var other in sameSimpleNameIdentities)
{
// only compare weak with weak
Debug.Assert(other.Identity is object);
if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity))
{
equivalent = other;
break;
}
}
}
if (equivalent.Identity == null)
{
sameSimpleNameIdentities.Add(referencedAssembly);
return null;
}
// equivalent found - ignore and/or report an error:
if (identity.IsStrongName)
{
Debug.Assert(equivalent.Identity.IsStrongName);
// versions might have been unified for a Framework assembly:
if (identity != equivalent.Identity)
{
// Dev12 C# reports an error
// Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used.
// BREAKING CHANGE in VB: we report an error for both languages
// Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.
MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity);
}
// If the versions match exactly we ignore duplicates w/o reporting errors while
// Dev12 C# reports:
// error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references.
// Dev12 VB reports:
// Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System.
// A second reference to 'D:\Temp\System.dll' cannot be added.
}
else
{
Debug.Assert(!equivalent.Identity.IsStrongName);
// Dev12 reports an error for all weak-named assemblies, even if the versions are the same.
// We treat assemblies with the same name and version equal even if they don't have a strong name.
// This change allows us to de-duplicate #r references based on identities rather than full paths,
// and is closer to platforms that don't support strong names and consider name and version enough
// to identify an assembly. An identity without version is considered to have version 0.0.0.0.
if (identity != equivalent.Identity)
{
MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity);
}
}
Debug.Assert(equivalent.Reference != null);
return equivalent.Reference;
}
protected void GetCompilationReferences(
TCompilation compilation,
DiagnosticBag diagnostics,
out ImmutableArray<MetadataReference> references,
out IDictionary<(string, string), MetadataReference> boundReferenceDirectives,
out ImmutableArray<Location> referenceDirectiveLocations)
{
ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance();
ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null;
IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null;
try
{
foreach (var referenceDirective in compilation.ReferenceDirectives)
{
Debug.Assert(referenceDirective.Location is object);
if (compilation.Options.MetadataReferenceResolver == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location));
break;
}
// we already successfully bound #r with the same value:
Debug.Assert(referenceDirective.File is object);
Debug.Assert(referenceDirective.Location.SourceTree is object);
if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File)))
{
continue;
}
MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation);
if (boundReference == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File));
continue;
}
if (localBoundReferenceDirectives == null)
{
localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>();
referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance();
}
referencesBuilder.Add(boundReference);
referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location);
localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference);
}
// add external reference at the end, so that they are processed first:
referencesBuilder.AddRange(compilation.ExternalReferences);
// Add all explicit references of the previous script compilation.
var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation;
if (previousScriptCompilation != null)
{
referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences);
}
if (localBoundReferenceDirectives == null)
{
// no directive references resolved successfully:
localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>();
}
boundReferenceDirectives = localBoundReferenceDirectives;
references = referencesBuilder.ToImmutable();
referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty;
}
finally
{
// Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and
// we don't want to clutter the test output with leak reports.
referencesBuilder.Free();
}
}
/// <summary>
/// For each given directive return a bound PE reference, or null if the binding fails.
/// </summary>
private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation)
{
var tree = location.SourceTree;
string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null;
// checked earlier:
Debug.Assert(compilation.Options.MetadataReferenceResolver != null);
var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true));
if (references.IsDefaultOrEmpty)
{
return null;
}
if (references.Length > 1)
{
// TODO: implement
throw new NotSupportedException();
}
return references[0];
}
internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies(
ImmutableArray<AssemblyIdentity> references,
ImmutableArray<AssemblyData> definitions,
int definitionStartIndex,
AssemblyIdentityComparer assemblyIdentityComparer)
{
var boundReferences = new AssemblyReferenceBinding[references.Length];
for (int j = 0; j < references.Length; j++)
{
boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer);
}
return boundReferences;
}
/// <summary>
/// Used to match AssemblyRef with AssemblyDef.
/// </summary>
/// <param name="definitions">Array of definition identities to match against.</param>
/// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param>
/// <param name="reference">Reference identity to resolve.</param>
/// <param name="assemblyIdentityComparer">Assembly identity comparer.</param>
/// <returns>
/// Returns an index the reference is bound.
/// </returns>
internal static AssemblyReferenceBinding ResolveReferencedAssembly(
AssemblyIdentity reference,
ImmutableArray<AssemblyData> definitions,
int definitionStartIndex,
AssemblyIdentityComparer assemblyIdentityComparer)
{
// Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version.
// For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version.
// If match.Version != reference.Version a warning is reported.
// definition with the lowest version higher than reference version, unless exact version found
int minHigherVersionDefinition = -1;
int maxLowerVersionDefinition = -1;
// Skip assembly being built for now; it will be considered at the very end:
bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0;
definitionStartIndex = Math.Max(definitionStartIndex, 1);
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
AssemblyIdentity definition = definitions[i].Identity;
switch (assemblyIdentityComparer.Compare(reference, definition))
{
case AssemblyIdentityComparer.ComparisonResult.NotEquivalent:
continue;
case AssemblyIdentityComparer.ComparisonResult.Equivalent:
return new AssemblyReferenceBinding(reference, i);
case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion:
if (reference.Version < definition.Version)
{
// Refers to an older assembly than we have
if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version)
{
minHigherVersionDefinition = i;
}
}
else
{
Debug.Assert(reference.Version > definition.Version);
// Refers to a newer assembly than we have
if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version)
{
maxLowerVersionDefinition = i;
}
}
continue;
default:
throw ExceptionUtilities.Unreachable;
}
}
// we haven't found definition that matches the reference
if (minHigherVersionDefinition != -1)
{
return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1);
}
if (maxLowerVersionDefinition != -1)
{
return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1);
}
// Handle cases where Windows.winmd is a runtime substitute for a
// reference to a compile-time winmd. This is for scenarios such as a
// debugger EE which constructs a compilation from the modules of
// the running process where Windows.winmd loaded at runtime is a
// substitute for a collection of Windows.*.winmd compile-time references.
if (reference.IsWindowsComponent())
{
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
if (definitions[i].Identity.IsWindowsRuntime())
{
return new AssemblyReferenceBinding(reference, i);
}
}
}
// In the IDE it is possible the reference we're looking for is a
// compilation reference to a source assembly. However, if the reference
// is of ContentType WindowsRuntime then the compilation will never
// match since all C#/VB WindowsRuntime compilations output .winmdobjs,
// not .winmds, and the ContentType of a .winmdobj is Default.
// If this is the case, we want to ignore the ContentType mismatch and
// allow the compilation to match the reference.
if (reference.ContentType == AssemblyContentType.WindowsRuntime)
{
for (int i = definitionStartIndex; i < definitions.Length; i++)
{
var definition = definitions[i].Identity;
var sourceCompilation = definitions[i].SourceCompilation;
if (definition.ContentType == AssemblyContentType.Default &&
sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata &&
AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) &&
reference.Version.Equals(definition.Version) &&
reference.IsRetargetable == definition.IsRetargetable &&
AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) &&
AssemblyIdentity.KeysEqual(reference, definition))
{
return new AssemblyReferenceBinding(reference, i);
}
}
}
// As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the
// compilation (i.e. source) assembly as a last resort. We follow the native approach of
// skipping the public key comparison since we have yet to compute it.
if (resolveAgainstAssemblyBeingBuilt &&
AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name))
{
Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty);
return new AssemblyReferenceBinding(reference, 0);
}
return new AssemblyReferenceBinding(reference);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/Dashboard.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal partial class Dashboard : UserControl, IDisposable
{
private readonly DashboardViewModel _model;
private readonly IWpfTextView _textView;
private readonly IAdornmentLayer _findAdornmentLayer;
private PresentationSource _presentationSource;
private DependencyObject _rootDependencyObject;
private IInputElement _rootInputElement;
private UIElement _focusedElement = null;
private readonly List<UIElement> _tabNavigableChildren;
private readonly IEditorFormatMap _textFormattingMap;
internal bool ShouldReceiveKeyboardNavigation { get; set; }
private readonly IEnumerable<string> _renameAccessKeys = new[]
{
RenameShortcutKey.RenameOverloads,
RenameShortcutKey.SearchInComments,
RenameShortcutKey.SearchInStrings,
RenameShortcutKey.Apply,
RenameShortcutKey.PreviewChanges
};
public Dashboard(
DashboardViewModel model,
IEditorFormatMapService editorFormatMapService,
IWpfTextView textView)
{
_model = model;
InitializeComponent();
_tabNavigableChildren = new UIElement[] { this.OverloadsCheckbox, this.CommentsCheckbox, this.StringsCheckbox, this.FileRenameCheckbox, this.PreviewChangesCheckbox, this.ApplyButton, this.CloseButton }.ToList();
_textView = textView;
this.DataContext = model;
this.Visibility = textView.HasAggregateFocus ? Visibility.Visible : Visibility.Collapsed;
_textView.GotAggregateFocus += OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus += OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged += OnElementSizeChanged;
this.SizeChanged += OnElementSizeChanged;
PresentationSource.AddSourceChangedHandler(this, OnPresentationSourceChanged);
try
{
_findAdornmentLayer = textView.GetAdornmentLayer("FindUIAdornmentLayer");
((UIElement)_findAdornmentLayer).LayoutUpdated += FindAdornmentCanvas_LayoutUpdated;
}
catch (ArgumentOutOfRangeException)
{
// Find UI doesn't exist in ETA.
}
// Once the Dashboard is loaded, the visual tree is completely created and the
// UIAutomation system has discovered and connected the AutomationPeer to the tree,
// allowing us to raise the AutomationFocusChanged event and have it process correctly.
// for us to set up the AutomationPeer
this.Loaded += Dashboard_Loaded;
if (editorFormatMapService != null)
{
_textFormattingMap = editorFormatMapService.GetEditorFormatMap("text");
_textFormattingMap.FormatMappingChanged += UpdateBorderColors;
UpdateBorderColors(this, eventArgs: null);
}
ResolvableConflictBorder.StrokeThickness = RenameFixupTagDefinition.StrokeThickness;
ResolvableConflictBorder.StrokeDashArray = new DoubleCollection(RenameFixupTagDefinition.StrokeDashArray);
UnresolvableConflictBorder.StrokeThickness = RenameConflictTagDefinition.StrokeThickness;
UnresolvableConflictBorder.StrokeDashArray = new DoubleCollection(RenameConflictTagDefinition.StrokeDashArray);
this.Focus();
textView.Caret.IsHidden = false;
ShouldReceiveKeyboardNavigation = false;
}
private void UpdateBorderColors(object sender, FormatItemsEventArgs eventArgs)
{
var resolvableConflictBrush = GetEditorTagBorderBrush(RenameFixupTag.TagId);
ResolvableConflictBorder.Stroke = resolvableConflictBrush;
ResolvableConflictText.Foreground = resolvableConflictBrush;
var unresolvableConflictBrush = GetEditorTagBorderBrush(RenameConflictTag.TagId);
UnresolvableConflictBorder.Stroke = unresolvableConflictBrush;
UnresolvableConflictText.Foreground = unresolvableConflictBrush;
ErrorText.Foreground = unresolvableConflictBrush;
}
private Brush GetEditorTagBorderBrush(string tagId)
{
var properties = _textFormattingMap.GetProperties(tagId);
return (Brush)(properties["Foreground"] ?? ((Pen)properties["MarkerFormatDefinition/BorderId"]).Brush);
}
private void Dashboard_Loaded(object sender, RoutedEventArgs e)
{
// Move automation focus to the Dashboard so that screenreaders will announce that the
// session has begun.
if (AutomationPeer.ListenerExists(AutomationEvents.AutomationFocusChanged))
{
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseAutomationEvent(AutomationEvents.AutomationFocusChanged);
}
}
private void ShowCaret()
{
// We actually want the caret visible even though the view isn't explicitly focused.
((UIElement)_textView.Caret).Visibility = Visibility.Visible;
}
private void FocusElement(UIElement firstElement, Func<int, int> selector)
{
if (_focusedElement == null)
{
_focusedElement = firstElement;
}
else
{
var current = _tabNavigableChildren.IndexOf(_focusedElement);
current = selector(current);
_focusedElement = _tabNavigableChildren[current];
}
// We have found the next control in _tabNavigableChildren, but not all controls are
// visible in all sessions. For example, "Rename Overloads" only applies if there the
// symbol has overloads. Therefore, continue searching for the next control in
// _tabNavigableChildren that's actually valid in this session.
while (!_focusedElement.IsVisible)
{
var current = _tabNavigableChildren.IndexOf(_focusedElement);
current = selector(current);
_focusedElement = _tabNavigableChildren[current];
}
_focusedElement.Focus();
ShowCaret();
}
internal void FocusNextElement()
=> FocusElement(_tabNavigableChildren.First(), i => i == _tabNavigableChildren.Count - 1 ? 0 : i + 1);
internal void FocusPreviousElement()
=> FocusElement(_tabNavigableChildren.Last(), i => i == 0 ? _tabNavigableChildren.Count - 1 : i - 1);
private void OnPresentationSourceChanged(object sender, SourceChangedEventArgs args)
{
if (args.NewSource == null)
{
this.DisconnectFromPresentationSource();
}
else
{
this.ConnectToPresentationSource(args.NewSource);
}
}
private void ConnectToPresentationSource(PresentationSource presentationSource)
{
_presentationSource = presentationSource ?? throw new ArgumentNullException(nameof(presentationSource));
if (Application.Current != null && Application.Current.MainWindow != null)
{
_rootDependencyObject = Application.Current.MainWindow as DependencyObject;
}
else
{
_rootDependencyObject = _presentationSource.RootVisual as DependencyObject;
}
_rootInputElement = _rootDependencyObject as IInputElement;
if (_rootDependencyObject != null && _rootInputElement != null)
{
foreach (var accessKey in _renameAccessKeys)
{
AccessKeyManager.Register(accessKey, _rootInputElement);
}
AccessKeyManager.AddAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
}
private void OnAccessKeyPressed(object sender, AccessKeyPressedEventArgs args)
{
foreach (var accessKey in _renameAccessKeys)
{
if (string.Compare(accessKey, args.Key, StringComparison.OrdinalIgnoreCase) == 0)
{
args.Target = this;
args.Handled = true;
return;
}
}
}
protected override void OnAccessKey(AccessKeyEventArgs e)
{
if (e != null)
{
if (string.Equals(e.Key, RenameShortcutKey.RenameOverloads, StringComparison.OrdinalIgnoreCase))
{
this.OverloadsCheckbox.IsChecked = !this.OverloadsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInComments, StringComparison.OrdinalIgnoreCase))
{
this.CommentsCheckbox.IsChecked = !this.CommentsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInStrings, StringComparison.OrdinalIgnoreCase))
{
this.StringsCheckbox.IsChecked = !this.StringsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.PreviewChanges, StringComparison.OrdinalIgnoreCase))
{
this.PreviewChangesCheckbox.IsChecked = !this.PreviewChangesCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.RenameFile, StringComparison.OrdinalIgnoreCase))
{
this.FileRenameCheckbox.IsChecked = !this.FileRenameCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.Apply, StringComparison.OrdinalIgnoreCase))
{
this.Commit();
}
}
}
protected override AutomationPeer OnCreateAutomationPeer()
=> new DashboardAutomationPeer(this, _model.OriginalName);
private void DisconnectFromPresentationSource()
{
if (_rootInputElement != null)
{
foreach (var registeredKey in _renameAccessKeys)
{
AccessKeyManager.Unregister(registeredKey, _rootInputElement);
}
AccessKeyManager.RemoveAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
_presentationSource = null;
_rootDependencyObject = null;
_rootInputElement = null;
}
private void FindAdornmentCanvas_LayoutUpdated(object sender, EventArgs e)
=> PositionDashboard();
#pragma warning disable CA1822 // Mark members as static - used in xaml
public string RenameOverloads => EditorFeaturesResources.Include_overload_s;
public Visibility RenameOverloadsVisibility => _model.RenameOverloadsVisibility;
public bool IsRenameOverloadsEditable => _model.IsRenameOverloadsEditable;
public string SearchInComments => EditorFeaturesResources.Include_comments;
public string SearchInStrings => EditorFeaturesResources.Include_strings;
public string ApplyRename => EditorFeaturesResources.Apply1;
public string CancelRename => EditorFeaturesResources.Cancel;
public string PreviewChanges => EditorFeaturesResources.Preview_changes1;
public string RenameInstructions => EditorFeaturesResources.Modify_any_highlighted_location_to_begin_renaming;
public string ApplyToolTip { get { return EditorFeaturesResources.Apply3 + " (Enter)"; } }
public string CancelToolTip { get { return EditorFeaturesResources.Cancel + " (Esc)"; } }
#pragma warning restore CA1822 // Mark members as static
private void OnElementSizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.WidthChanged)
{
PositionDashboard();
}
}
private void PositionDashboard()
{
var top = _textView.ViewportTop;
if (_findAdornmentLayer != null && _findAdornmentLayer.Elements.Count != 0)
{
var adornment = _findAdornmentLayer.Elements[0].Adornment;
top += adornment.RenderSize.Height;
}
Canvas.SetTop(this, top);
Canvas.SetLeft(this, _textView.ViewportLeft + _textView.VisualElement.RenderSize.Width - this.RenderSize.Width);
}
private void OnTextViewGotAggregateFocus(object sender, EventArgs e)
{
this.Visibility = Visibility.Visible;
PositionDashboard();
}
private void OnTextViewLostAggregateFocus(object sender, EventArgs e)
=> this.Visibility = Visibility.Collapsed;
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
_model.Session.Cancel();
_textView.VisualElement.Focus();
}
private void Apply_Click(object sender, RoutedEventArgs e)
=> Commit();
private void Commit()
{
try
{
_model.Session.Commit();
_textView.VisualElement.Focus();
}
catch (NotSupportedException ex)
{
// Session.Commit can throw if it can't commit
// rename operation.
// handle that case gracefully
var notificationService = _model.Session.Workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(ex.Message, title: EditorFeaturesResources.Rename, severity: NotificationSeverity.Error);
}
catch (Exception ex) when (FatalError.ReportAndCatch(ex))
{
// Show a nice error to the user via an info bar
var errorReportingService = _model.Session.Workspace.Services.GetService<IErrorReportingService>();
if (errorReportingService is null)
{
return;
}
errorReportingService.ShowGlobalErrorInfo(
string.Format(EditorFeaturesWpfResources.Error_performing_rename_0, ex.Message),
new InfoBarUI(
WorkspacesResources.Show_Stack_Trace,
InfoBarUI.UIKind.HyperLink,
() => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true));
}
}
public void Dispose()
{
_textView.GotAggregateFocus -= OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus -= OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged -= OnElementSizeChanged;
this.SizeChanged -= OnElementSizeChanged;
if (_findAdornmentLayer != null)
{
((UIElement)_findAdornmentLayer).LayoutUpdated -= FindAdornmentCanvas_LayoutUpdated;
}
if (_textFormattingMap != null)
{
_textFormattingMap.FormatMappingChanged -= UpdateBorderColors;
}
this.Loaded -= Dashboard_Loaded;
_model.Dispose();
PresentationSource.RemoveSourceChangedHandler(this, OnPresentationSourceChanged);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnGotFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// Don't send clicks into the text editor below.
e.Handled = true;
}
protected override void OnMouseUp(MouseButtonEventArgs e)
=> e.Handled = true;
protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
{
base.OnIsKeyboardFocusWithinChanged(e);
ShouldReceiveKeyboardNavigation = (bool)e.NewValue;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal partial class Dashboard : UserControl, IDisposable
{
private readonly DashboardViewModel _model;
private readonly IWpfTextView _textView;
private readonly IAdornmentLayer _findAdornmentLayer;
private PresentationSource _presentationSource;
private DependencyObject _rootDependencyObject;
private IInputElement _rootInputElement;
private UIElement _focusedElement = null;
private readonly List<UIElement> _tabNavigableChildren;
private readonly IEditorFormatMap _textFormattingMap;
internal bool ShouldReceiveKeyboardNavigation { get; set; }
private readonly IEnumerable<string> _renameAccessKeys = new[]
{
RenameShortcutKey.RenameOverloads,
RenameShortcutKey.SearchInComments,
RenameShortcutKey.SearchInStrings,
RenameShortcutKey.Apply,
RenameShortcutKey.PreviewChanges
};
public Dashboard(
DashboardViewModel model,
IEditorFormatMapService editorFormatMapService,
IWpfTextView textView)
{
_model = model;
InitializeComponent();
_tabNavigableChildren = new UIElement[] { this.OverloadsCheckbox, this.CommentsCheckbox, this.StringsCheckbox, this.FileRenameCheckbox, this.PreviewChangesCheckbox, this.ApplyButton, this.CloseButton }.ToList();
_textView = textView;
this.DataContext = model;
this.Visibility = textView.HasAggregateFocus ? Visibility.Visible : Visibility.Collapsed;
_textView.GotAggregateFocus += OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus += OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged += OnElementSizeChanged;
this.SizeChanged += OnElementSizeChanged;
PresentationSource.AddSourceChangedHandler(this, OnPresentationSourceChanged);
try
{
_findAdornmentLayer = textView.GetAdornmentLayer("FindUIAdornmentLayer");
((UIElement)_findAdornmentLayer).LayoutUpdated += FindAdornmentCanvas_LayoutUpdated;
}
catch (ArgumentOutOfRangeException)
{
// Find UI doesn't exist in ETA.
}
// Once the Dashboard is loaded, the visual tree is completely created and the
// UIAutomation system has discovered and connected the AutomationPeer to the tree,
// allowing us to raise the AutomationFocusChanged event and have it process correctly.
// for us to set up the AutomationPeer
this.Loaded += Dashboard_Loaded;
if (editorFormatMapService != null)
{
_textFormattingMap = editorFormatMapService.GetEditorFormatMap("text");
_textFormattingMap.FormatMappingChanged += UpdateBorderColors;
UpdateBorderColors(this, eventArgs: null);
}
ResolvableConflictBorder.StrokeThickness = RenameFixupTagDefinition.StrokeThickness;
ResolvableConflictBorder.StrokeDashArray = new DoubleCollection(RenameFixupTagDefinition.StrokeDashArray);
UnresolvableConflictBorder.StrokeThickness = RenameConflictTagDefinition.StrokeThickness;
UnresolvableConflictBorder.StrokeDashArray = new DoubleCollection(RenameConflictTagDefinition.StrokeDashArray);
this.Focus();
textView.Caret.IsHidden = false;
ShouldReceiveKeyboardNavigation = false;
}
private void UpdateBorderColors(object sender, FormatItemsEventArgs eventArgs)
{
var resolvableConflictBrush = GetEditorTagBorderBrush(RenameFixupTag.TagId);
ResolvableConflictBorder.Stroke = resolvableConflictBrush;
ResolvableConflictText.Foreground = resolvableConflictBrush;
var unresolvableConflictBrush = GetEditorTagBorderBrush(RenameConflictTag.TagId);
UnresolvableConflictBorder.Stroke = unresolvableConflictBrush;
UnresolvableConflictText.Foreground = unresolvableConflictBrush;
ErrorText.Foreground = unresolvableConflictBrush;
}
private Brush GetEditorTagBorderBrush(string tagId)
{
var properties = _textFormattingMap.GetProperties(tagId);
return (Brush)(properties["Foreground"] ?? ((Pen)properties["MarkerFormatDefinition/BorderId"]).Brush);
}
private void Dashboard_Loaded(object sender, RoutedEventArgs e)
{
// Move automation focus to the Dashboard so that screenreaders will announce that the
// session has begun.
if (AutomationPeer.ListenerExists(AutomationEvents.AutomationFocusChanged))
{
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseAutomationEvent(AutomationEvents.AutomationFocusChanged);
}
}
private void ShowCaret()
{
// We actually want the caret visible even though the view isn't explicitly focused.
((UIElement)_textView.Caret).Visibility = Visibility.Visible;
}
private void FocusElement(UIElement firstElement, Func<int, int> selector)
{
if (_focusedElement == null)
{
_focusedElement = firstElement;
}
else
{
var current = _tabNavigableChildren.IndexOf(_focusedElement);
current = selector(current);
_focusedElement = _tabNavigableChildren[current];
}
// We have found the next control in _tabNavigableChildren, but not all controls are
// visible in all sessions. For example, "Rename Overloads" only applies if there the
// symbol has overloads. Therefore, continue searching for the next control in
// _tabNavigableChildren that's actually valid in this session.
while (!_focusedElement.IsVisible)
{
var current = _tabNavigableChildren.IndexOf(_focusedElement);
current = selector(current);
_focusedElement = _tabNavigableChildren[current];
}
_focusedElement.Focus();
ShowCaret();
}
internal void FocusNextElement()
=> FocusElement(_tabNavigableChildren.First(), i => i == _tabNavigableChildren.Count - 1 ? 0 : i + 1);
internal void FocusPreviousElement()
=> FocusElement(_tabNavigableChildren.Last(), i => i == 0 ? _tabNavigableChildren.Count - 1 : i - 1);
private void OnPresentationSourceChanged(object sender, SourceChangedEventArgs args)
{
if (args.NewSource == null)
{
this.DisconnectFromPresentationSource();
}
else
{
this.ConnectToPresentationSource(args.NewSource);
}
}
private void ConnectToPresentationSource(PresentationSource presentationSource)
{
_presentationSource = presentationSource ?? throw new ArgumentNullException(nameof(presentationSource));
if (Application.Current != null && Application.Current.MainWindow != null)
{
_rootDependencyObject = Application.Current.MainWindow as DependencyObject;
}
else
{
_rootDependencyObject = _presentationSource.RootVisual as DependencyObject;
}
_rootInputElement = _rootDependencyObject as IInputElement;
if (_rootDependencyObject != null && _rootInputElement != null)
{
foreach (var accessKey in _renameAccessKeys)
{
AccessKeyManager.Register(accessKey, _rootInputElement);
}
AccessKeyManager.AddAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
}
private void OnAccessKeyPressed(object sender, AccessKeyPressedEventArgs args)
{
foreach (var accessKey in _renameAccessKeys)
{
if (string.Compare(accessKey, args.Key, StringComparison.OrdinalIgnoreCase) == 0)
{
args.Target = this;
args.Handled = true;
return;
}
}
}
protected override void OnAccessKey(AccessKeyEventArgs e)
{
if (e != null)
{
if (string.Equals(e.Key, RenameShortcutKey.RenameOverloads, StringComparison.OrdinalIgnoreCase))
{
this.OverloadsCheckbox.IsChecked = !this.OverloadsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInComments, StringComparison.OrdinalIgnoreCase))
{
this.CommentsCheckbox.IsChecked = !this.CommentsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInStrings, StringComparison.OrdinalIgnoreCase))
{
this.StringsCheckbox.IsChecked = !this.StringsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.PreviewChanges, StringComparison.OrdinalIgnoreCase))
{
this.PreviewChangesCheckbox.IsChecked = !this.PreviewChangesCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.RenameFile, StringComparison.OrdinalIgnoreCase))
{
this.FileRenameCheckbox.IsChecked = !this.FileRenameCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.Apply, StringComparison.OrdinalIgnoreCase))
{
this.Commit();
}
}
}
protected override AutomationPeer OnCreateAutomationPeer()
=> new DashboardAutomationPeer(this, _model.OriginalName);
private void DisconnectFromPresentationSource()
{
if (_rootInputElement != null)
{
foreach (var registeredKey in _renameAccessKeys)
{
AccessKeyManager.Unregister(registeredKey, _rootInputElement);
}
AccessKeyManager.RemoveAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
_presentationSource = null;
_rootDependencyObject = null;
_rootInputElement = null;
}
private void FindAdornmentCanvas_LayoutUpdated(object sender, EventArgs e)
=> PositionDashboard();
#pragma warning disable CA1822 // Mark members as static - used in xaml
public string RenameOverloads => EditorFeaturesResources.Include_overload_s;
public Visibility RenameOverloadsVisibility => _model.RenameOverloadsVisibility;
public bool IsRenameOverloadsEditable => _model.IsRenameOverloadsEditable;
public string SearchInComments => EditorFeaturesResources.Include_comments;
public string SearchInStrings => EditorFeaturesResources.Include_strings;
public string ApplyRename => EditorFeaturesResources.Apply1;
public string CancelRename => EditorFeaturesResources.Cancel;
public string PreviewChanges => EditorFeaturesResources.Preview_changes1;
public string RenameInstructions => EditorFeaturesResources.Modify_any_highlighted_location_to_begin_renaming;
public string ApplyToolTip { get { return EditorFeaturesResources.Apply3 + " (Enter)"; } }
public string CancelToolTip { get { return EditorFeaturesResources.Cancel + " (Esc)"; } }
#pragma warning restore CA1822 // Mark members as static
private void OnElementSizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.WidthChanged)
{
PositionDashboard();
}
}
private void PositionDashboard()
{
var top = _textView.ViewportTop;
if (_findAdornmentLayer != null && _findAdornmentLayer.Elements.Count != 0)
{
var adornment = _findAdornmentLayer.Elements[0].Adornment;
top += adornment.RenderSize.Height;
}
Canvas.SetTop(this, top);
Canvas.SetLeft(this, _textView.ViewportLeft + _textView.VisualElement.RenderSize.Width - this.RenderSize.Width);
}
private void OnTextViewGotAggregateFocus(object sender, EventArgs e)
{
this.Visibility = Visibility.Visible;
PositionDashboard();
}
private void OnTextViewLostAggregateFocus(object sender, EventArgs e)
=> this.Visibility = Visibility.Collapsed;
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
_model.Session.Cancel();
_textView.VisualElement.Focus();
}
private void Apply_Click(object sender, RoutedEventArgs e)
=> Commit();
private void Commit()
{
try
{
_model.Session.Commit();
_textView.VisualElement.Focus();
}
catch (NotSupportedException ex)
{
// Session.Commit can throw if it can't commit
// rename operation.
// handle that case gracefully
var notificationService = _model.Session.Workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(ex.Message, title: EditorFeaturesResources.Rename, severity: NotificationSeverity.Error);
}
catch (Exception ex) when (FatalError.ReportAndCatch(ex))
{
// Show a nice error to the user via an info bar
var errorReportingService = _model.Session.Workspace.Services.GetService<IErrorReportingService>();
if (errorReportingService is null)
{
return;
}
errorReportingService.ShowGlobalErrorInfo(
string.Format(EditorFeaturesWpfResources.Error_performing_rename_0, ex.Message),
new InfoBarUI(
WorkspacesResources.Show_Stack_Trace,
InfoBarUI.UIKind.HyperLink,
() => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true));
}
}
public void Dispose()
{
_textView.GotAggregateFocus -= OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus -= OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged -= OnElementSizeChanged;
this.SizeChanged -= OnElementSizeChanged;
if (_findAdornmentLayer != null)
{
((UIElement)_findAdornmentLayer).LayoutUpdated -= FindAdornmentCanvas_LayoutUpdated;
}
if (_textFormattingMap != null)
{
_textFormattingMap.FormatMappingChanged -= UpdateBorderColors;
}
this.Loaded -= Dashboard_Loaded;
_model.Dispose();
PresentationSource.RemoveSourceChangedHandler(this, OnPresentationSourceChanged);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnGotFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// Don't send clicks into the text editor below.
e.Handled = true;
}
protected override void OnMouseUp(MouseButtonEventArgs e)
=> e.Handled = true;
protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
{
base.OnIsKeyboardFocusWithinChanged(e);
ShouldReceiveKeyboardNavigation = (bool)e.NewValue;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared]
internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public UseCoalesceExpressionForNullableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(conditionalExpression,
(c, g) =>
{
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
var coalesceExpression = whenPart == whenTrue
? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue))
: g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse));
if (semanticFacts.IsInExpressionTree(
semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken))
{
coalesceExpression = coalesceExpression.WithAdditionalAnnotations(
WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime));
}
return coalesceExpression;
});
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
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.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared]
internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public UseCoalesceExpressionForNullableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(conditionalExpression,
(c, g) =>
{
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
var coalesceExpression = whenPart == whenTrue
? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue))
: g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse));
if (semanticFacts.IsInExpressionTree(
semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken))
{
coalesceExpression = coalesceExpression.WithAdditionalAnnotations(
WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime));
}
return coalesceExpression;
});
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression))
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/CSharpTest/Structure/DestructorDeclarationStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<DestructorDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructor()
{
const string code = @"
class C
{
{|hint:$$~C(){|textspan:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructorWithComments()
{
const string code = @"
class C
{
{|span1:// Goo
// Bar|}
{|hint2:$$~C(){|textspan2:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("span1", "// Goo ...", autoCollapse: true),
Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructorMissingCloseParenAndBody()
{
// Expected behavior is that the class should be outlined, but the destructor should not.
const string code = @"
class C
{
$$~C(
}";
await VerifyNoBlockSpansAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<DestructorDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructor()
{
const string code = @"
class C
{
{|hint:$$~C(){|textspan:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructorWithComments()
{
const string code = @"
class C
{
{|span1:// Goo
// Bar|}
{|hint2:$$~C(){|textspan2:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("span1", "// Goo ...", autoCollapse: true),
Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDestructorMissingCloseParenAndBody()
{
// Expected behavior is that the class should be outlined, but the destructor should not.
const string code = @"
class C
{
$$~C(
}";
await VerifyNoBlockSpansAsync(code);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFileHeaderDiagnosticAnalyzer(string language)
: base(
IDEDiagnosticIds.FileHeaderMismatch,
EnforceOnBuildValues.FileHeaderMismatch,
CodeStyleOptions2.FileHeaderTemplate,
language,
new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_is_missing_a_required_header), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
RoslynDebug.AssertNotNull(DescriptorId);
var invalidHeaderTitle = new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
var invalidHeaderMessage = new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_contains_a_header_that_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
InvalidHeaderDescriptor = CreateDescriptorWithId(DescriptorId, EnforceOnBuildValues.FileHeaderMismatch, invalidHeaderTitle, invalidHeaderMessage);
}
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
internal DiagnosticDescriptor MissingHeaderDescriptor => Descriptor;
internal DiagnosticDescriptor InvalidHeaderDescriptor { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(HandleSyntaxTree);
private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
var tree = context.Tree;
var root = tree.GetRoot(context.CancellationToken);
// don't process empty files
if (root.FullSpan.IsEmpty)
{
return;
}
if (!context.Options.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
|| string.IsNullOrEmpty(fileHeaderTemplate))
{
return;
}
var fileHeader = FileHeaderHelper.ParseFileHeader(root);
if (fileHeader.IsMissing)
{
context.ReportDiagnostic(Diagnostic.Create(MissingHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(tree.FilePath));
if (!CompareCopyrightText(expectedFileHeader, fileHeader.CopyrightText))
{
context.ReportDiagnostic(Diagnostic.Create(InvalidHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
}
private static bool CompareCopyrightText(string expectedFileHeader, string copyrightText)
{
// make sure that both \n and \r\n are accepted from the settings.
var reformattedCopyrightTextParts = expectedFileHeader.Replace("\r\n", "\n").Split('\n');
var fileHeaderCopyrightTextParts = copyrightText.Replace("\r\n", "\n").Split('\n');
if (reformattedCopyrightTextParts.Length != fileHeaderCopyrightTextParts.Length)
{
return false;
}
// compare line by line, ignoring leading and trailing whitespace on each line.
for (var i = 0; i < reformattedCopyrightTextParts.Length; i++)
{
if (string.CompareOrdinal(reformattedCopyrightTextParts[i].Trim(), fileHeaderCopyrightTextParts[i].Trim()) != 0)
{
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.IO;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFileHeaderDiagnosticAnalyzer(string language)
: base(
IDEDiagnosticIds.FileHeaderMismatch,
EnforceOnBuildValues.FileHeaderMismatch,
CodeStyleOptions2.FileHeaderTemplate,
language,
new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_is_missing_a_required_header), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
RoslynDebug.AssertNotNull(DescriptorId);
var invalidHeaderTitle = new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
var invalidHeaderMessage = new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_contains_a_header_that_does_not_match_the_required_text), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
InvalidHeaderDescriptor = CreateDescriptorWithId(DescriptorId, EnforceOnBuildValues.FileHeaderMismatch, invalidHeaderTitle, invalidHeaderMessage);
}
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
internal DiagnosticDescriptor MissingHeaderDescriptor => Descriptor;
internal DiagnosticDescriptor InvalidHeaderDescriptor { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(HandleSyntaxTree);
private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
var tree = context.Tree;
var root = tree.GetRoot(context.CancellationToken);
// don't process empty files
if (root.FullSpan.IsEmpty)
{
return;
}
if (!context.Options.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
|| string.IsNullOrEmpty(fileHeaderTemplate))
{
return;
}
var fileHeader = FileHeaderHelper.ParseFileHeader(root);
if (fileHeader.IsMissing)
{
context.ReportDiagnostic(Diagnostic.Create(MissingHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(tree.FilePath));
if (!CompareCopyrightText(expectedFileHeader, fileHeader.CopyrightText))
{
context.ReportDiagnostic(Diagnostic.Create(InvalidHeaderDescriptor, fileHeader.GetLocation(tree)));
return;
}
}
private static bool CompareCopyrightText(string expectedFileHeader, string copyrightText)
{
// make sure that both \n and \r\n are accepted from the settings.
var reformattedCopyrightTextParts = expectedFileHeader.Replace("\r\n", "\n").Split('\n');
var fileHeaderCopyrightTextParts = copyrightText.Replace("\r\n", "\n").Split('\n');
if (reformattedCopyrightTextParts.Length != fileHeaderCopyrightTextParts.Length)
{
return false;
}
// compare line by line, ignoring leading and trailing whitespace on each line.
for (var i = 0; i < reformattedCopyrightTextParts.Length; i++)
{
if (string.CompareOrdinal(reformattedCopyrightTextParts[i].Trim(), fileHeaderCopyrightTextParts[i].Trim()) != 0)
{
return false;
}
}
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ExpressionCompiler :
IDkmClrExpressionCompiler,
IDkmClrExpressionCompilerCallback,
IDkmModuleModifiedNotification,
IDkmModuleInstanceUnloadNotification,
IDkmLanguageFrameDecoder,
IDkmLanguageInstructionDecoder
{
// Need to support IDkmLanguageFrameDecoder and IDkmLanguageInstructionDecoder
// See https://github.com/dotnet/roslyn/issues/22620
private readonly IDkmLanguageFrameDecoder _languageFrameDecoder;
private readonly IDkmLanguageInstructionDecoder _languageInstructionDecoder;
private readonly bool _useReferencedAssembliesOnly;
public ExpressionCompiler(IDkmLanguageFrameDecoder languageFrameDecoder, IDkmLanguageInstructionDecoder languageInstructionDecoder)
{
_languageFrameDecoder = languageFrameDecoder;
_languageInstructionDecoder = languageInstructionDecoder;
_useReferencedAssembliesOnly = GetUseReferencedAssembliesOnlySetting();
}
DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
DkmInspectionContext inspectionContext,
DkmClrInstructionAddress instructionAddress,
bool argumentsOnly)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = argumentsOnly
? ImmutableArray<Alias>.Empty
: GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
string? error;
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var builder = ArrayBuilder<LocalAndMethod>.GetInstance();
var assembly = context.CompileGetLocals(
builder,
argumentsOnly,
aliases,
diagnostics,
out var typeName,
testData: null);
Debug.Assert((builder.Count == 0) == (assembly.Count == 0));
var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo));
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
out error);
return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, r.Assembly, r.TypeName, r.Locals);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ImmutableArray<Alias> GetAliases(DkmClrRuntimeInstance runtimeInstance, DkmInspectionContext inspectionContext)
{
var dkmAliases = runtimeInstance.GetAliases(inspectionContext);
if (dkmAliases == null)
{
return ImmutableArray<Alias>.Empty;
}
var builder = ArrayBuilder<Alias>.GetInstance(dkmAliases.Count);
foreach (var dkmAlias in dkmAliases)
{
builder.Add(new Alias(
dkmAlias.Kind,
dkmAlias.Name,
dkmAlias.FullName,
dkmAlias.Type,
dkmAlias.CustomTypeInfoPayloadTypeId,
dkmAlias.CustomTypeInfoPayload));
}
return builder.ToImmutableAndFree();
}
void IDkmClrExpressionCompiler.CompileExpression(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmInspectionContext inspectionContext,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileExpression(
expression.Text,
expression.CompilationFlags,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileAssignment(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmEvaluationResult lValue,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileAssignment(
lValue.FullName,
expression.Text,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
Debug.Assert(
r.CompileResult == null && r.ResultProperties.Flags == default ||
(r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
DkmLanguageExpression expression,
DkmClrModuleInstance moduleInstance,
int token,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
var compileResult = CompileWithRetry(
appDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
(context, diagnostics) =>
{
return context.CompileExpression(
expression.Text,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out var unusedResultProperties,
testData: null);
},
out error);
result = compileResult.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool GetUseReferencedAssembliesOnlySetting()
{
return RegistryHelpers.GetBoolRegistryValue("UseReferencedAssembliesOnly");
}
internal MakeAssemblyReferencesKind GetMakeAssemblyReferencesKind(bool useReferencedModulesOnly)
{
if (useReferencedModulesOnly)
{
return MakeAssemblyReferencesKind.DirectReferencesOnly;
}
return _useReferencedAssembliesOnly ? MakeAssemblyReferencesKind.AllReferences : MakeAssemblyReferencesKind.AllAssemblies;
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references)
{
var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities);
if (newReferences.Length > 0)
{
references = references.AddRange(newReferences);
return true;
}
return false;
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
RemoveDataItemIfNecessary(moduleInstance);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
RemoveDataItemIfNecessary(moduleInstance);
}
#region IDkmLanguageFrameDecoder, IDkmLanguageInstructionDecoder
void IDkmLanguageFrameDecoder.GetFrameName(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine);
}
void IDkmLanguageFrameDecoder.GetFrameReturnType(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameReturnType(inspectionContext, workList, frame, completionRoutine);
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
return _languageInstructionDecoder.GetMethodName(languageInstructionAddress, argumentFlags);
}
#endregion
private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance)
{
// If the module is not a managed module, the module change has no effect.
var module = moduleInstance as DkmClrModuleInstance;
if (module == null)
{
return;
}
// Drop any context cached on the AppDomain.
var appDomain = module.AppDomain;
RemoveDataItem(appDomain);
}
internal abstract DiagnosticFormatter DiagnosticFormatter { get; }
internal abstract DkmCompilerId CompilerId { get; }
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly);
internal abstract EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly);
internal abstract void RemoveDataItem(DkmClrAppDomain appDomain);
internal abstract ImmutableArray<MetadataBlock> GetMetadataBlocks(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance);
private EvaluationContextBase CreateMethodContext(
DkmClrInstructionAddress instructionAddress,
ImmutableArray<MetadataBlock> metadataBlocks,
bool useReferencedModulesOnly)
{
var moduleInstance = instructionAddress.ModuleInstance;
var methodToken = instructionAddress.MethodId.Token;
int localSignatureToken;
try
{
localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken);
}
catch (InvalidOperationException)
{
// No local signature. May occur when debugging .dmp.
localSignatureToken = 0;
}
catch (FileNotFoundException)
{
// No local signature. May occur when debugging heapless dumps.
localSignatureToken = 0;
}
return CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
moduleVersionId: moduleInstance.Mvid,
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: instructionAddress.ILOffset,
localSignatureToken: localSignatureToken,
useReferencedModulesOnly: useReferencedModulesOnly);
}
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics);
private TResult CompileWithRetry<TResult>(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
out string? errorMessage)
{
var metadataBlocks = GetMetadataBlocks(appDomain, runtimeInstance);
return CompileWithRetry(
metadataBlocks,
DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
out errorMessage);
}
internal static TResult CompileWithRetry<TResult>(
ImmutableArray<MetadataBlock> metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string? errorMessage)
{
TResult compileResult;
PooledHashSet<AssemblyIdentity>? assembliesLoadedInRetryLoop = null;
bool tryAgain;
var linqLibrary = EvaluationContextBase.SystemLinqIdentity;
do
{
errorMessage = null;
var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
if (diagnostics.HasAnyErrors())
{
errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
diagnostics,
formatter,
preferredUICulture: null,
linqLibrary: linqLibrary,
useReferencedModulesOnly: out var useReferencedModulesOnly,
missingAssemblyIdentities: out var missingAssemblyIdentities);
// If there were LINQ-related errors, we'll initially add System.Linq (set above).
// If that doesn't work, we'll fall back to System.Core for subsequent retries.
linqLibrary = EvaluationContextBase.SystemCoreIdentity;
// Can we remove the `useReferencedModulesOnly` attempt if we're only using
// modules reachable from the current module? In short, can we avoid retrying?
if (useReferencedModulesOnly)
{
Debug.Assert(missingAssemblyIdentities.IsEmpty);
var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true);
var otherDiagnostics = DiagnosticBag.GetInstance();
var otherResult = compile(otherContext, otherDiagnostics);
if (!otherDiagnostics.HasAnyErrors())
{
errorMessage = null;
compileResult = otherResult;
}
otherDiagnostics.Free();
}
else
{
if (!missingAssemblyIdentities.IsEmpty)
{
if (assembliesLoadedInRetryLoop == null)
{
assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance();
}
// If any identities failed to add (they were already in the list), then don't retry.
if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
{
tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
}
}
}
}
diagnostics.Free();
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
return compileResult;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
{
ReadOnlyCollection<byte>? customTypeInfo;
Guid customTypeInfoId = local.GetCustomTypeInfo(out customTypeInfo);
return DkmClrLocalVariableInfo.Create(
local.LocalDisplayName,
local.LocalName,
local.MethodName,
local.Flags,
DkmEvaluationResultCategory.Data,
customTypeInfo.ToCustomTypeInfo(customTypeInfoId));
}
private readonly struct GetLocalsResult
{
internal readonly string TypeName;
internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals;
internal readonly ReadOnlyCollection<byte> Assembly;
internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly)
{
TypeName = typeName;
Locals = locals;
Assembly = assembly;
}
}
private readonly struct CompileExpressionResult
{
internal readonly CompileResult? CompileResult;
internal readonly ResultProperties ResultProperties;
internal CompileExpressionResult(CompileResult? compileResult, ResultProperties resultProperties)
{
CompileResult = compileResult;
ResultProperties = resultProperties;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ExpressionCompiler :
IDkmClrExpressionCompiler,
IDkmClrExpressionCompilerCallback,
IDkmModuleModifiedNotification,
IDkmModuleInstanceUnloadNotification,
IDkmLanguageFrameDecoder,
IDkmLanguageInstructionDecoder
{
// Need to support IDkmLanguageFrameDecoder and IDkmLanguageInstructionDecoder
// See https://github.com/dotnet/roslyn/issues/22620
private readonly IDkmLanguageFrameDecoder _languageFrameDecoder;
private readonly IDkmLanguageInstructionDecoder _languageInstructionDecoder;
private readonly bool _useReferencedAssembliesOnly;
public ExpressionCompiler(IDkmLanguageFrameDecoder languageFrameDecoder, IDkmLanguageInstructionDecoder languageInstructionDecoder)
{
_languageFrameDecoder = languageFrameDecoder;
_languageInstructionDecoder = languageInstructionDecoder;
_useReferencedAssembliesOnly = GetUseReferencedAssembliesOnlySetting();
}
DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
DkmInspectionContext inspectionContext,
DkmClrInstructionAddress instructionAddress,
bool argumentsOnly)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = argumentsOnly
? ImmutableArray<Alias>.Empty
: GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
string? error;
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var builder = ArrayBuilder<LocalAndMethod>.GetInstance();
var assembly = context.CompileGetLocals(
builder,
argumentsOnly,
aliases,
diagnostics,
out var typeName,
testData: null);
Debug.Assert((builder.Count == 0) == (assembly.Count == 0));
var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo));
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
out error);
return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, r.Assembly, r.TypeName, r.Locals);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ImmutableArray<Alias> GetAliases(DkmClrRuntimeInstance runtimeInstance, DkmInspectionContext inspectionContext)
{
var dkmAliases = runtimeInstance.GetAliases(inspectionContext);
if (dkmAliases == null)
{
return ImmutableArray<Alias>.Empty;
}
var builder = ArrayBuilder<Alias>.GetInstance(dkmAliases.Count);
foreach (var dkmAlias in dkmAliases)
{
builder.Add(new Alias(
dkmAlias.Kind,
dkmAlias.Name,
dkmAlias.FullName,
dkmAlias.Type,
dkmAlias.CustomTypeInfoPayloadTypeId,
dkmAlias.CustomTypeInfoPayload));
}
return builder.ToImmutableAndFree();
}
void IDkmClrExpressionCompiler.CompileExpression(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmInspectionContext inspectionContext,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileExpression(
expression.Text,
expression.CompilationFlags,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileAssignment(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmEvaluationResult lValue,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileAssignment(
lValue.FullName,
expression.Text,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
Debug.Assert(
r.CompileResult == null && r.ResultProperties.Flags == default ||
(r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
DkmLanguageExpression expression,
DkmClrModuleInstance moduleInstance,
int token,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
var compileResult = CompileWithRetry(
appDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
(context, diagnostics) =>
{
return context.CompileExpression(
expression.Text,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out var unusedResultProperties,
testData: null);
},
out error);
result = compileResult.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool GetUseReferencedAssembliesOnlySetting()
{
return RegistryHelpers.GetBoolRegistryValue("UseReferencedAssembliesOnly");
}
internal MakeAssemblyReferencesKind GetMakeAssemblyReferencesKind(bool useReferencedModulesOnly)
{
if (useReferencedModulesOnly)
{
return MakeAssemblyReferencesKind.DirectReferencesOnly;
}
return _useReferencedAssembliesOnly ? MakeAssemblyReferencesKind.AllReferences : MakeAssemblyReferencesKind.AllAssemblies;
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references)
{
var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities);
if (newReferences.Length > 0)
{
references = references.AddRange(newReferences);
return true;
}
return false;
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
RemoveDataItemIfNecessary(moduleInstance);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
RemoveDataItemIfNecessary(moduleInstance);
}
#region IDkmLanguageFrameDecoder, IDkmLanguageInstructionDecoder
void IDkmLanguageFrameDecoder.GetFrameName(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine);
}
void IDkmLanguageFrameDecoder.GetFrameReturnType(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameReturnType(inspectionContext, workList, frame, completionRoutine);
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
return _languageInstructionDecoder.GetMethodName(languageInstructionAddress, argumentFlags);
}
#endregion
private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance)
{
// If the module is not a managed module, the module change has no effect.
var module = moduleInstance as DkmClrModuleInstance;
if (module == null)
{
return;
}
// Drop any context cached on the AppDomain.
var appDomain = module.AppDomain;
RemoveDataItem(appDomain);
}
internal abstract DiagnosticFormatter DiagnosticFormatter { get; }
internal abstract DkmCompilerId CompilerId { get; }
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly);
internal abstract EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly);
internal abstract void RemoveDataItem(DkmClrAppDomain appDomain);
internal abstract ImmutableArray<MetadataBlock> GetMetadataBlocks(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance);
private EvaluationContextBase CreateMethodContext(
DkmClrInstructionAddress instructionAddress,
ImmutableArray<MetadataBlock> metadataBlocks,
bool useReferencedModulesOnly)
{
var moduleInstance = instructionAddress.ModuleInstance;
var methodToken = instructionAddress.MethodId.Token;
int localSignatureToken;
try
{
localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken);
}
catch (InvalidOperationException)
{
// No local signature. May occur when debugging .dmp.
localSignatureToken = 0;
}
catch (FileNotFoundException)
{
// No local signature. May occur when debugging heapless dumps.
localSignatureToken = 0;
}
return CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
moduleVersionId: moduleInstance.Mvid,
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: instructionAddress.ILOffset,
localSignatureToken: localSignatureToken,
useReferencedModulesOnly: useReferencedModulesOnly);
}
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics);
private TResult CompileWithRetry<TResult>(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
out string? errorMessage)
{
var metadataBlocks = GetMetadataBlocks(appDomain, runtimeInstance);
return CompileWithRetry(
metadataBlocks,
DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
out errorMessage);
}
internal static TResult CompileWithRetry<TResult>(
ImmutableArray<MetadataBlock> metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string? errorMessage)
{
TResult compileResult;
PooledHashSet<AssemblyIdentity>? assembliesLoadedInRetryLoop = null;
bool tryAgain;
var linqLibrary = EvaluationContextBase.SystemLinqIdentity;
do
{
errorMessage = null;
var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
if (diagnostics.HasAnyErrors())
{
errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
diagnostics,
formatter,
preferredUICulture: null,
linqLibrary: linqLibrary,
useReferencedModulesOnly: out var useReferencedModulesOnly,
missingAssemblyIdentities: out var missingAssemblyIdentities);
// If there were LINQ-related errors, we'll initially add System.Linq (set above).
// If that doesn't work, we'll fall back to System.Core for subsequent retries.
linqLibrary = EvaluationContextBase.SystemCoreIdentity;
// Can we remove the `useReferencedModulesOnly` attempt if we're only using
// modules reachable from the current module? In short, can we avoid retrying?
if (useReferencedModulesOnly)
{
Debug.Assert(missingAssemblyIdentities.IsEmpty);
var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true);
var otherDiagnostics = DiagnosticBag.GetInstance();
var otherResult = compile(otherContext, otherDiagnostics);
if (!otherDiagnostics.HasAnyErrors())
{
errorMessage = null;
compileResult = otherResult;
}
otherDiagnostics.Free();
}
else
{
if (!missingAssemblyIdentities.IsEmpty)
{
if (assembliesLoadedInRetryLoop == null)
{
assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance();
}
// If any identities failed to add (they were already in the list), then don't retry.
if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
{
tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
}
}
}
}
diagnostics.Free();
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
return compileResult;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
{
ReadOnlyCollection<byte>? customTypeInfo;
Guid customTypeInfoId = local.GetCustomTypeInfo(out customTypeInfo);
return DkmClrLocalVariableInfo.Create(
local.LocalDisplayName,
local.LocalName,
local.MethodName,
local.Flags,
DkmEvaluationResultCategory.Data,
customTypeInfo.ToCustomTypeInfo(customTypeInfoId));
}
private readonly struct GetLocalsResult
{
internal readonly string TypeName;
internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals;
internal readonly ReadOnlyCollection<byte> Assembly;
internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly)
{
TypeName = typeName;
Locals = locals;
Assembly = assembly;
}
}
private readonly struct CompileExpressionResult
{
internal readonly CompileResult? CompileResult;
internal readonly ResultProperties ResultProperties;
internal CompileExpressionResult(CompileResult? compileResult, ResultProperties resultProperties)
{
CompileResult = compileResult;
ResultProperties = resultProperties;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/Core/Portable/Workspace/Host/Caching/IProjectCacheService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Service used to enable recoverable object caches for a given <see cref="ProjectId"/>
/// </summary>
internal interface IProjectCacheService : IWorkspaceService
{
IDisposable EnableCaching(ProjectId key);
}
/// <summary>
/// Caches recoverable objects
///
/// Compilations are put into a conditional weak table.
///
/// Recoverable SyntaxTrees implement <see cref="ICachedObjectOwner"/> since they are numerous
/// and putting them into a conditional weak table greatly increases GC costs in
/// clr.dll!PromoteDependentHandle.
/// </summary>
internal interface IProjectCacheHostService : IProjectCacheService
{
/// <summary>
/// If caching is enabled for <see cref="ProjectId"/> key, the instance is added to
/// a conditional weak table.
///
/// It will not be collected until either caching is disabled for the project
/// or the owner object is collected.
///
/// If caching is not enabled for the project, the instance is added to a fixed-size
/// cache.
/// </summary>
/// <returns>The instance passed in is always returned</returns>
[return: NotNullIfNotNull("instance")]
T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class;
/// <summary>
/// If caching is enabled for <see cref="ProjectId"/> key, <see cref="ICachedObjectOwner.CachedObject"/>
/// will be set to instance.
/// </summary>
/// <returns>The instance passed in is always returned</returns>
[return: NotNullIfNotNull("instance")]
T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Service used to enable recoverable object caches for a given <see cref="ProjectId"/>
/// </summary>
internal interface IProjectCacheService : IWorkspaceService
{
IDisposable EnableCaching(ProjectId key);
}
/// <summary>
/// Caches recoverable objects
///
/// Compilations are put into a conditional weak table.
///
/// Recoverable SyntaxTrees implement <see cref="ICachedObjectOwner"/> since they are numerous
/// and putting them into a conditional weak table greatly increases GC costs in
/// clr.dll!PromoteDependentHandle.
/// </summary>
internal interface IProjectCacheHostService : IProjectCacheService
{
/// <summary>
/// If caching is enabled for <see cref="ProjectId"/> key, the instance is added to
/// a conditional weak table.
///
/// It will not be collected until either caching is disabled for the project
/// or the owner object is collected.
///
/// If caching is not enabled for the project, the instance is added to a fixed-size
/// cache.
/// </summary>
/// <returns>The instance passed in is always returned</returns>
[return: NotNullIfNotNull("instance")]
T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class;
/// <summary>
/// If caching is enabled for <see cref="ProjectId"/> key, <see cref="ICachedObjectOwner.CachedObject"/>
/// will be set to instance.
/// </summary>
/// <returns>The instance passed in is always returned</returns>
[return: NotNullIfNotNull("instance")]
T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class;
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferencePropertiesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Test/Diagnostics/PerfMargin/PerfMarginPanel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Roslyn.Hosting.Diagnostics.PerfMargin
{
public class PerfMarginPanel : UserControl
{
private static readonly DataModel s_model = new DataModel();
private static readonly PerfEventActivityLogger s_logger = new PerfEventActivityLogger(s_model);
private readonly ListView _mainListView;
private readonly Grid _mainGrid;
private readonly DispatcherTimer _timer;
private readonly List<StatusIndicator> _indicators = new List<StatusIndicator>();
private ListView _detailsListView;
private bool _stopTimer;
public PerfMarginPanel()
{
Logger.SetLogger(AggregateLogger.AddOrReplace(s_logger, Logger.GetLogger(), l => l is PerfEventActivityLogger));
// grid
_mainGrid = new Grid();
_mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
_mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
_mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
// set diagnostic list
_mainListView = CreateContent(new ActivityLevel[] { s_model.RootNode }.Concat(s_model.RootNode.Children), useWrapPanel: true);
_mainListView.SelectionChanged += OnPerfItemsListSelectionChanged;
Grid.SetRow(_mainListView, 0);
_mainGrid.Children.Add(_mainListView);
this.Content = _mainGrid;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, UpdateUI, this.Dispatcher);
StartTimer();
s_model.RootNode.IsActiveChanged += (s, e) =>
{
if (_stopTimer)
{
StartTimer();
}
};
}
private void StartTimer()
{
_timer.Start();
_stopTimer = false;
}
private void UpdateUI(object sender, EventArgs e)
{
foreach (var item in _indicators)
{
item.UpdateOnUIThread();
}
if (_stopTimer)
{
_timer.Stop();
}
else
{
// Stop it next time if there was no activity.
_stopTimer = true;
}
}
private ListView CreateContent(IEnumerable<ActivityLevel> items, bool useWrapPanel)
{
var listView = new ListView();
foreach (var item in items)
{
StackPanel s = new StackPanel() { Orientation = Orientation.Horizontal };
////g.HorizontalAlignment = HorizontalAlignment.Stretch;
StatusIndicator indicator = new StatusIndicator(item);
indicator.Subscribe();
indicator.Width = 30;
indicator.Height = 10;
s.Children.Add(indicator);
_indicators.Add(indicator);
TextBlock label = new TextBlock();
label.Text = item.Name;
Grid.SetColumn(label, 1);
s.Children.Add(label);
s.ToolTip = item.Name;
s.Tag = item;
listView.Items.Add(s);
}
if (useWrapPanel)
{
listView.SelectionMode = SelectionMode.Single;
listView.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
var wrapPanelFactory = new FrameworkElementFactory(typeof(WrapPanel));
wrapPanelFactory.SetValue(WrapPanel.ItemWidthProperty, 120d);
listView.ItemsPanel = new ItemsPanelTemplate(wrapPanelFactory);
}
return listView;
}
private void OnPerfItemsListSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_detailsListView != null)
{
_mainGrid.ColumnDefinitions.RemoveAt(1);
_mainGrid.Children.Remove(_detailsListView);
foreach (StackPanel item in _detailsListView.Items)
{
var indicator = item.Children[0] as StatusIndicator;
_indicators.Remove(indicator);
indicator.Unsubscribe();
}
_detailsListView = null;
}
var selectedItem = _mainListView.SelectedItem as StackPanel;
if (selectedItem == null)
{
return;
}
if (selectedItem.Tag is ActivityLevel context && context.Children != null && context.Children.Any())
{
_detailsListView = CreateContent(context.Children, useWrapPanel: false);
_mainGrid.Children.Add(_detailsListView);
_mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
Grid.SetColumn(_detailsListView, 1);
// Update the UI
StartTimer();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Roslyn.Hosting.Diagnostics.PerfMargin
{
public class PerfMarginPanel : UserControl
{
private static readonly DataModel s_model = new DataModel();
private static readonly PerfEventActivityLogger s_logger = new PerfEventActivityLogger(s_model);
private readonly ListView _mainListView;
private readonly Grid _mainGrid;
private readonly DispatcherTimer _timer;
private readonly List<StatusIndicator> _indicators = new List<StatusIndicator>();
private ListView _detailsListView;
private bool _stopTimer;
public PerfMarginPanel()
{
Logger.SetLogger(AggregateLogger.AddOrReplace(s_logger, Logger.GetLogger(), l => l is PerfEventActivityLogger));
// grid
_mainGrid = new Grid();
_mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
_mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
_mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
// set diagnostic list
_mainListView = CreateContent(new ActivityLevel[] { s_model.RootNode }.Concat(s_model.RootNode.Children), useWrapPanel: true);
_mainListView.SelectionChanged += OnPerfItemsListSelectionChanged;
Grid.SetRow(_mainListView, 0);
_mainGrid.Children.Add(_mainListView);
this.Content = _mainGrid;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, UpdateUI, this.Dispatcher);
StartTimer();
s_model.RootNode.IsActiveChanged += (s, e) =>
{
if (_stopTimer)
{
StartTimer();
}
};
}
private void StartTimer()
{
_timer.Start();
_stopTimer = false;
}
private void UpdateUI(object sender, EventArgs e)
{
foreach (var item in _indicators)
{
item.UpdateOnUIThread();
}
if (_stopTimer)
{
_timer.Stop();
}
else
{
// Stop it next time if there was no activity.
_stopTimer = true;
}
}
private ListView CreateContent(IEnumerable<ActivityLevel> items, bool useWrapPanel)
{
var listView = new ListView();
foreach (var item in items)
{
StackPanel s = new StackPanel() { Orientation = Orientation.Horizontal };
////g.HorizontalAlignment = HorizontalAlignment.Stretch;
StatusIndicator indicator = new StatusIndicator(item);
indicator.Subscribe();
indicator.Width = 30;
indicator.Height = 10;
s.Children.Add(indicator);
_indicators.Add(indicator);
TextBlock label = new TextBlock();
label.Text = item.Name;
Grid.SetColumn(label, 1);
s.Children.Add(label);
s.ToolTip = item.Name;
s.Tag = item;
listView.Items.Add(s);
}
if (useWrapPanel)
{
listView.SelectionMode = SelectionMode.Single;
listView.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
var wrapPanelFactory = new FrameworkElementFactory(typeof(WrapPanel));
wrapPanelFactory.SetValue(WrapPanel.ItemWidthProperty, 120d);
listView.ItemsPanel = new ItemsPanelTemplate(wrapPanelFactory);
}
return listView;
}
private void OnPerfItemsListSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_detailsListView != null)
{
_mainGrid.ColumnDefinitions.RemoveAt(1);
_mainGrid.Children.Remove(_detailsListView);
foreach (StackPanel item in _detailsListView.Items)
{
var indicator = item.Children[0] as StatusIndicator;
_indicators.Remove(indicator);
indicator.Unsubscribe();
}
_detailsListView = null;
}
var selectedItem = _mainListView.SelectedItem as StackPanel;
if (selectedItem == null)
{
return;
}
if (selectedItem.Tag is ActivityLevel context && context.Children != null && context.Children.Any())
{
_detailsListView = CreateContent(context.Children, useWrapPanel: false);
_mainGrid.Children.Add(_detailsListView);
_mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
Grid.SetColumn(_detailsListView, 1);
// Update the UI
StartTimer();
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Log/LogAggregator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal class LogAggregator : AbstractLogAggregator<LogAggregator.Counter>
{
protected override Counter CreateCounter()
=> new();
public void SetCount(object key, int count)
{
var counter = GetCounter(key);
counter.SetCount(count);
}
public void IncreaseCount(object key)
{
var counter = GetCounter(key);
counter.IncreaseCount();
}
public void IncreaseCountBy(object key, int value)
{
var counter = GetCounter(key);
counter.IncreaseCountBy(value);
}
public int GetCount(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetCount();
}
return 0;
}
internal sealed class Counter
{
private int _count;
public void SetCount(int count)
=> _count = count;
public void IncreaseCount()
{
// Counter class probably not needed. but it is here for 2 reasons.
// make handling concurrency easier and be a place holder for different type of counter
Interlocked.Increment(ref _count);
}
public void IncreaseCountBy(int value)
{
// Counter class probably not needed. but it is here for 2 reasons.
// make handling concurrency easier and be a place holder for different type of counter
Interlocked.Add(ref _count, value);
}
public int GetCount()
=> _count;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal class LogAggregator : AbstractLogAggregator<LogAggregator.Counter>
{
protected override Counter CreateCounter()
=> new();
public void SetCount(object key, int count)
{
var counter = GetCounter(key);
counter.SetCount(count);
}
public void IncreaseCount(object key)
{
var counter = GetCounter(key);
counter.IncreaseCount();
}
public void IncreaseCountBy(object key, int value)
{
var counter = GetCounter(key);
counter.IncreaseCountBy(value);
}
public int GetCount(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetCount();
}
return 0;
}
internal sealed class Counter
{
private int _count;
public void SetCount(int count)
=> _count = count;
public void IncreaseCount()
{
// Counter class probably not needed. but it is here for 2 reasons.
// make handling concurrency easier and be a place holder for different type of counter
Interlocked.Increment(ref _count);
}
public void IncreaseCountBy(int value)
{
// Counter class probably not needed. but it is here for 2 reasons.
// make handling concurrency easier and be a place holder for different type of counter
Interlocked.Add(ref _count, value);
}
public int GetCount()
=> _count;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal struct ExternalSourceInfo
{
public readonly int? StartLine;
public readonly bool Ends;
public ExternalSourceInfo(int? startLine, bool ends)
{
this.StartLine = startLine;
this.Ends = ends;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal struct ExternalSourceInfo
{
public readonly int? StartLine;
public readonly bool Ends;
public ExternalSourceInfo(int? startLine, bool ends)
{
this.StartLine = startLine;
this.Ends = ends;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpDebuggerIntelliSenseContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
internal class CSharpDebuggerIntelliSenseContext : AbstractDebuggerIntelliSenseContext
{
public CSharpDebuggerIntelliSenseContext(
IWpfTextView view,
IVsTextView vsTextView,
IVsTextLines debuggerBuffer,
ITextBuffer contextBuffer,
TextSpan[] currentStatementSpan,
IComponentModel componentModel,
IServiceProvider serviceProvider)
: base(view,
vsTextView,
debuggerBuffer,
contextBuffer,
currentStatementSpan,
componentModel,
serviceProvider,
componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType))
{
}
// Test constructor
internal CSharpDebuggerIntelliSenseContext(
IWpfTextView view,
ITextBuffer contextBuffer,
TextSpan[] currentStatementSpan,
IComponentModel componentModel,
bool immediateWindow)
: base(view,
contextBuffer,
currentStatementSpan,
componentModel,
componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType),
immediateWindow)
{
}
protected override int GetAdjustedContextPoint(int contextPoint, Document document)
{
// Determine the position in the buffer at which to end the tracking span representing
// the part of the imaginary buffer before the text in the view.
var tree = document.GetSyntaxTreeSynchronously(CancellationToken.None);
var token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None);
// Special case to handle class designer because it asks for debugger IntelliSense using
// spans between members.
if (contextPoint > token.Span.End &&
token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block) &&
token.Parent.Parent is MemberDeclarationSyntax)
{
return contextPoint;
}
if (token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block))
{
return token.SpanStart;
}
return token.FullSpan.End;
}
protected override ITrackingSpan GetPreviousStatementBufferAndSpan(int contextPoint, Document document)
{
var previousTrackingSpan = ContextBuffer.CurrentSnapshot.CreateTrackingSpan(Span.FromBounds(0, contextPoint), SpanTrackingMode.EdgeNegative);
// terminate the previous expression/statement
var buffer = ProjectionBufferFactoryService.CreateProjectionBuffer(
projectionEditResolver: null,
sourceSpans: new object[] { previousTrackingSpan, this.StatementTerminator },
options: ProjectionBufferOptions.None,
contentType: this.ContentType);
return buffer.CurrentSnapshot.CreateTrackingSpan(0, buffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeNegative);
}
public override bool CompletionStartsOnQuestionMark
{
get { return false; }
}
protected override string StatementTerminator
{
get { return ";"; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
internal class CSharpDebuggerIntelliSenseContext : AbstractDebuggerIntelliSenseContext
{
public CSharpDebuggerIntelliSenseContext(
IWpfTextView view,
IVsTextView vsTextView,
IVsTextLines debuggerBuffer,
ITextBuffer contextBuffer,
TextSpan[] currentStatementSpan,
IComponentModel componentModel,
IServiceProvider serviceProvider)
: base(view,
vsTextView,
debuggerBuffer,
contextBuffer,
currentStatementSpan,
componentModel,
serviceProvider,
componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType))
{
}
// Test constructor
internal CSharpDebuggerIntelliSenseContext(
IWpfTextView view,
ITextBuffer contextBuffer,
TextSpan[] currentStatementSpan,
IComponentModel componentModel,
bool immediateWindow)
: base(view,
contextBuffer,
currentStatementSpan,
componentModel,
componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType),
immediateWindow)
{
}
protected override int GetAdjustedContextPoint(int contextPoint, Document document)
{
// Determine the position in the buffer at which to end the tracking span representing
// the part of the imaginary buffer before the text in the view.
var tree = document.GetSyntaxTreeSynchronously(CancellationToken.None);
var token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None);
// Special case to handle class designer because it asks for debugger IntelliSense using
// spans between members.
if (contextPoint > token.Span.End &&
token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block) &&
token.Parent.Parent is MemberDeclarationSyntax)
{
return contextPoint;
}
if (token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block))
{
return token.SpanStart;
}
return token.FullSpan.End;
}
protected override ITrackingSpan GetPreviousStatementBufferAndSpan(int contextPoint, Document document)
{
var previousTrackingSpan = ContextBuffer.CurrentSnapshot.CreateTrackingSpan(Span.FromBounds(0, contextPoint), SpanTrackingMode.EdgeNegative);
// terminate the previous expression/statement
var buffer = ProjectionBufferFactoryService.CreateProjectionBuffer(
projectionEditResolver: null,
sourceSpans: new object[] { previousTrackingSpan, this.StatementTerminator },
options: ProjectionBufferOptions.None,
contentType: this.ContentType);
return buffer.CurrentSnapshot.CreateTrackingSpan(0, buffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeNegative);
}
public override bool CompletionStartsOnQuestionMark
{
get { return false; }
}
protected override string StatementTerminator
{
get { return ";"; }
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpEESymbolProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpEESymbolProvider : EESymbolProvider<TypeSymbol, LocalSymbol>
{
private readonly MetadataDecoder _metadataDecoder;
private readonly SourceAssemblySymbol _sourceAssembly;
private readonly PEMethodSymbol _method;
public CSharpEESymbolProvider(SourceAssemblySymbol sourceAssembly, PEModuleSymbol module, PEMethodSymbol method)
{
_metadataDecoder = new MetadataDecoder(module, method);
_sourceAssembly = sourceAssembly;
_method = method;
}
public override LocalSymbol GetLocalVariable(
string? name,
int slotIndex,
LocalInfo<TypeSymbol> info,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
var isPinned = info.IsPinned;
LocalDeclarationKind kind;
RefKind refKind;
TypeSymbol type;
if (info.IsByRef && isPinned)
{
kind = LocalDeclarationKind.FixedVariable;
refKind = RefKind.None;
type = new PointerTypeSymbol(TypeWithAnnotations.Create(info.Type));
}
else
{
kind = LocalDeclarationKind.RegularVariable;
refKind = info.IsByRef ? RefKind.Ref : RefKind.None;
type = info.Type;
}
// Custom modifiers can be dropped since binding ignores custom
// modifiers from locals and since we only need to preserve
// the type of the original local in the generated method.
type = IncludeDynamicAndTupleElementNamesIfAny(type, refKind, dynamicFlagsOpt, tupleElementNamesOpt);
return new EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, refKind, isPinned, isCompilerGenerated: false, canScheduleToStack: false);
}
public override LocalSymbol GetLocalConstant(
string name,
TypeSymbol type,
ConstantValue value,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
type = IncludeDynamicAndTupleElementNamesIfAny(type, RefKind.None, dynamicFlagsOpt, tupleElementNamesOpt);
return new EELocalConstantSymbol(_method, name, type, value);
}
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public override TypeSymbol DecodeLocalVariableType(ImmutableArray<byte> signature)
{
return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature);
}
public override TypeSymbol GetTypeSymbolForSerializedType(string typeName)
{
return _metadataDecoder.GetTypeSymbolForSerializedType(typeName);
}
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public override void DecodeLocalConstant(ref BlobReader reader, out TypeSymbol type, out ConstantValue value)
{
_metadataDecoder.DecodeLocalConstantBlobOrThrow(ref reader, out type, out value);
}
/// <exception cref="BadImageFormatException"></exception>
public override IAssemblySymbolInternal GetReferencedAssembly(AssemblyReferenceHandle handle)
{
int index = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle);
var assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index);
if (assembly == null)
{
throw new BadImageFormatException();
}
return assembly;
}
/// <exception cref="UnsupportedSignatureContent"></exception>
public override TypeSymbol GetType(EntityHandle handle)
{
bool isNoPiaLocalType;
return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, out isNoPiaLocalType, allowTypeSpec: true, requireShortForm: false);
}
private TypeSymbol IncludeDynamicAndTupleElementNamesIfAny(
TypeSymbol type,
RefKind refKind,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
if (!dynamicFlagsOpt.IsDefault)
{
type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(type, _sourceAssembly, refKind, dynamicFlagsOpt, checkLength: false);
}
return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpEESymbolProvider : EESymbolProvider<TypeSymbol, LocalSymbol>
{
private readonly MetadataDecoder _metadataDecoder;
private readonly SourceAssemblySymbol _sourceAssembly;
private readonly PEMethodSymbol _method;
public CSharpEESymbolProvider(SourceAssemblySymbol sourceAssembly, PEModuleSymbol module, PEMethodSymbol method)
{
_metadataDecoder = new MetadataDecoder(module, method);
_sourceAssembly = sourceAssembly;
_method = method;
}
public override LocalSymbol GetLocalVariable(
string? name,
int slotIndex,
LocalInfo<TypeSymbol> info,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
var isPinned = info.IsPinned;
LocalDeclarationKind kind;
RefKind refKind;
TypeSymbol type;
if (info.IsByRef && isPinned)
{
kind = LocalDeclarationKind.FixedVariable;
refKind = RefKind.None;
type = new PointerTypeSymbol(TypeWithAnnotations.Create(info.Type));
}
else
{
kind = LocalDeclarationKind.RegularVariable;
refKind = info.IsByRef ? RefKind.Ref : RefKind.None;
type = info.Type;
}
// Custom modifiers can be dropped since binding ignores custom
// modifiers from locals and since we only need to preserve
// the type of the original local in the generated method.
type = IncludeDynamicAndTupleElementNamesIfAny(type, refKind, dynamicFlagsOpt, tupleElementNamesOpt);
return new EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, refKind, isPinned, isCompilerGenerated: false, canScheduleToStack: false);
}
public override LocalSymbol GetLocalConstant(
string name,
TypeSymbol type,
ConstantValue value,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
type = IncludeDynamicAndTupleElementNamesIfAny(type, RefKind.None, dynamicFlagsOpt, tupleElementNamesOpt);
return new EELocalConstantSymbol(_method, name, type, value);
}
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public override TypeSymbol DecodeLocalVariableType(ImmutableArray<byte> signature)
{
return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature);
}
public override TypeSymbol GetTypeSymbolForSerializedType(string typeName)
{
return _metadataDecoder.GetTypeSymbolForSerializedType(typeName);
}
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public override void DecodeLocalConstant(ref BlobReader reader, out TypeSymbol type, out ConstantValue value)
{
_metadataDecoder.DecodeLocalConstantBlobOrThrow(ref reader, out type, out value);
}
/// <exception cref="BadImageFormatException"></exception>
public override IAssemblySymbolInternal GetReferencedAssembly(AssemblyReferenceHandle handle)
{
int index = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle);
var assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index);
if (assembly == null)
{
throw new BadImageFormatException();
}
return assembly;
}
/// <exception cref="UnsupportedSignatureContent"></exception>
public override TypeSymbol GetType(EntityHandle handle)
{
bool isNoPiaLocalType;
return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, out isNoPiaLocalType, allowTypeSpec: true, requireShortForm: false);
}
private TypeSymbol IncludeDynamicAndTupleElementNamesIfAny(
TypeSymbol type,
RefKind refKind,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt)
{
if (!dynamicFlagsOpt.IsDefault)
{
type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(type, _sourceAssembly, refKind, dynamicFlagsOpt, checkLength: false);
}
return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core/Implementation/IntelliSense/AbstractController.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal abstract class AbstractController<TSession, TModel, TPresenterSession, TEditorSession> : ForegroundThreadAffinitizedObject, IController<TModel>
where TSession : class, ISession<TModel>
where TPresenterSession : IIntelliSensePresenterSession
{
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected readonly IIntelliSensePresenter<TPresenterSession, TEditorSession> Presenter;
protected readonly IDocumentProvider DocumentProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly string _asyncOperationId;
// Null when we absolutely know we don't have any sort of item computation going on. Non
// null the moment we think we start computing state. Null again once we decide we can
// stop.
protected TSession sessionOpt;
protected bool IsSessionActive => sessionOpt != null;
protected AbstractController(IThreadingContext threadingContext, ITextView textView, ITextBuffer subjectBuffer, IIntelliSensePresenter<TPresenterSession, TEditorSession> presenter, IAsynchronousOperationListener asyncListener, IDocumentProvider documentProvider, string asyncOperationId)
: base(threadingContext)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.Presenter = presenter;
_asyncListener = asyncListener;
this.DocumentProvider = documentProvider;
_asyncOperationId = asyncOperationId;
this.TextView.Closed += OnTextViewClosed;
// Caret position changed only fires if the caret is explicitly moved. It doesn't fire
// when the caret is moved because of text change events.
this.TextView.Caret.PositionChanged += this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged += this.OnTextViewBufferPostChanged;
}
internal abstract void OnModelUpdated(TModel result, bool updateController);
internal abstract void OnTextViewBufferPostChanged(object sender, EventArgs e);
internal abstract void OnCaretPositionChanged(object sender, EventArgs e);
private void OnTextViewClosed(object sender, EventArgs e)
{
AssertIsForeground();
DismissSessionIfActive();
this.TextView.Closed -= OnTextViewClosed;
this.TextView.Caret.PositionChanged -= this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged -= this.OnTextViewBufferPostChanged;
}
public TModel WaitForController()
{
AssertIsForeground();
VerifySessionIsActive();
return sessionOpt.WaitForController();
}
void IController<TModel>.OnModelUpdated(TModel result, bool updateController)
{
// This is only called from the model computation if it was not cancelled. And if it was
// not cancelled then we must have a pointer to it (as well as the presenter session).
AssertIsForeground();
VerifySessionIsActive();
this.OnModelUpdated(result, updateController);
}
IAsyncToken IController<TModel>.BeginAsyncOperation(string name, object tag, string filePath, int lineNumber)
{
AssertIsForeground();
VerifySessionIsActive();
name = String.IsNullOrEmpty(name)
? _asyncOperationId
: $"{_asyncOperationId} - {name}";
return _asyncListener.BeginAsyncOperation(name, tag, filePath: filePath, lineNumber: lineNumber);
}
protected void VerifySessionIsActive()
{
AssertIsForeground();
Contract.ThrowIfFalse(IsSessionActive);
}
protected void VerifySessionIsInactive()
{
AssertIsForeground();
Contract.ThrowIfTrue(IsSessionActive);
}
protected void DismissSessionIfActive()
{
AssertIsForeground();
if (IsSessionActive)
{
this.StopModelComputation();
}
}
public void StopModelComputation()
{
AssertIsForeground();
VerifySessionIsActive();
// Make a local copy so that we won't do anything that causes us to recurse and try to
// dismiss this again.
var localSession = sessionOpt;
sessionOpt = null;
localSession.Stop();
}
public bool TryHandleEscapeKey()
{
AssertIsForeground();
// Escape simply dismissed a session if it's up. Otherwise let the next thing in the
// chain handle us.
if (!IsSessionActive)
{
return false;
}
// If we haven't even computed a model yet, then also send this command to anyone
// listening. It's unlikely that the command was intended for us (as we wouldn't
// have even shown ui yet.
var handledCommand = sessionOpt.InitialUnfilteredModel != null;
// In the presence of an escape, we always stop what we're doing.
this.StopModelComputation();
return handledCommand;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal abstract class AbstractController<TSession, TModel, TPresenterSession, TEditorSession> : ForegroundThreadAffinitizedObject, IController<TModel>
where TSession : class, ISession<TModel>
where TPresenterSession : IIntelliSensePresenterSession
{
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected readonly IIntelliSensePresenter<TPresenterSession, TEditorSession> Presenter;
protected readonly IDocumentProvider DocumentProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly string _asyncOperationId;
// Null when we absolutely know we don't have any sort of item computation going on. Non
// null the moment we think we start computing state. Null again once we decide we can
// stop.
protected TSession sessionOpt;
protected bool IsSessionActive => sessionOpt != null;
protected AbstractController(IThreadingContext threadingContext, ITextView textView, ITextBuffer subjectBuffer, IIntelliSensePresenter<TPresenterSession, TEditorSession> presenter, IAsynchronousOperationListener asyncListener, IDocumentProvider documentProvider, string asyncOperationId)
: base(threadingContext)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.Presenter = presenter;
_asyncListener = asyncListener;
this.DocumentProvider = documentProvider;
_asyncOperationId = asyncOperationId;
this.TextView.Closed += OnTextViewClosed;
// Caret position changed only fires if the caret is explicitly moved. It doesn't fire
// when the caret is moved because of text change events.
this.TextView.Caret.PositionChanged += this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged += this.OnTextViewBufferPostChanged;
}
internal abstract void OnModelUpdated(TModel result, bool updateController);
internal abstract void OnTextViewBufferPostChanged(object sender, EventArgs e);
internal abstract void OnCaretPositionChanged(object sender, EventArgs e);
private void OnTextViewClosed(object sender, EventArgs e)
{
AssertIsForeground();
DismissSessionIfActive();
this.TextView.Closed -= OnTextViewClosed;
this.TextView.Caret.PositionChanged -= this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged -= this.OnTextViewBufferPostChanged;
}
public TModel WaitForController()
{
AssertIsForeground();
VerifySessionIsActive();
return sessionOpt.WaitForController();
}
void IController<TModel>.OnModelUpdated(TModel result, bool updateController)
{
// This is only called from the model computation if it was not cancelled. And if it was
// not cancelled then we must have a pointer to it (as well as the presenter session).
AssertIsForeground();
VerifySessionIsActive();
this.OnModelUpdated(result, updateController);
}
IAsyncToken IController<TModel>.BeginAsyncOperation(string name, object tag, string filePath, int lineNumber)
{
AssertIsForeground();
VerifySessionIsActive();
name = String.IsNullOrEmpty(name)
? _asyncOperationId
: $"{_asyncOperationId} - {name}";
return _asyncListener.BeginAsyncOperation(name, tag, filePath: filePath, lineNumber: lineNumber);
}
protected void VerifySessionIsActive()
{
AssertIsForeground();
Contract.ThrowIfFalse(IsSessionActive);
}
protected void VerifySessionIsInactive()
{
AssertIsForeground();
Contract.ThrowIfTrue(IsSessionActive);
}
protected void DismissSessionIfActive()
{
AssertIsForeground();
if (IsSessionActive)
{
this.StopModelComputation();
}
}
public void StopModelComputation()
{
AssertIsForeground();
VerifySessionIsActive();
// Make a local copy so that we won't do anything that causes us to recurse and try to
// dismiss this again.
var localSession = sessionOpt;
sessionOpt = null;
localSession.Stop();
}
public bool TryHandleEscapeKey()
{
AssertIsForeground();
// Escape simply dismissed a session if it's up. Otherwise let the next thing in the
// chain handle us.
if (!IsSessionActive)
{
return false;
}
// If we haven't even computed a model yet, then also send this command to anyone
// listening. It's unlikely that the command was intended for us (as we wouldn't
// have even shown ui yet.
var handledCommand = sessionOpt.InitialUnfilteredModel != null;
// In the presence of an escape, we always stop what we're doing.
this.StopModelComputation();
return handledCommand;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/CSharp/Portable/Symbols/Source/AttributeLocation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
[Flags]
internal enum AttributeLocation : short
{
None = 0,
// the order of these determine the order in which they are displayed in error messages when multiple locations are possible:
Assembly = 1 << 0,
Module = 1 << 1,
Type = 1 << 2,
Method = 1 << 3,
Field = 1 << 4,
Property = 1 << 5,
Event = 1 << 6,
Parameter = 1 << 7,
Return = 1 << 8,
TypeParameter = 1 << 9,
// must be the last:
Unknown = 1 << 10,
}
internal static class AttributeLocationExtensions
{
internal static string ToDisplayString(this AttributeLocation locations)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i < (int)AttributeLocation.Unknown; i <<= 1)
{
if ((locations & (AttributeLocation)i) != 0)
{
if (result.Length > 0)
{
result.Append(", ");
}
switch ((AttributeLocation)i)
{
case AttributeLocation.Assembly:
result.Append("assembly");
break;
case AttributeLocation.Module:
result.Append("module");
break;
case AttributeLocation.Type:
result.Append("type");
break;
case AttributeLocation.Method:
result.Append("method");
break;
case AttributeLocation.Field:
result.Append("field");
break;
case AttributeLocation.Property:
result.Append("property");
break;
case AttributeLocation.Event:
result.Append("event");
break;
case AttributeLocation.Return:
result.Append("return");
break;
case AttributeLocation.Parameter:
result.Append("param");
break;
case AttributeLocation.TypeParameter:
result.Append("typevar");
break;
default:
throw ExceptionUtilities.UnexpectedValue(i);
}
}
}
return result.ToString();
}
internal static AttributeLocation ToAttributeLocation(this SyntaxToken token)
{
// NOTE: to match dev10, we're using the value text, rather
// than the actual text. For example, "@return" is equivalent
// to "return".
return ToAttributeLocation(token.ValueText);
}
internal static AttributeLocation ToAttributeLocation(this Syntax.InternalSyntax.SyntaxToken token)
{
// NOTE: to match dev10, we're using the value text, rather
// than the actual text. For example, "@return" is equivalent
// to "return".
return ToAttributeLocation(token.ValueText);
}
private static AttributeLocation ToAttributeLocation(string text)
{
switch (text)
{
case "assembly":
return AttributeLocation.Assembly;
case "module":
return AttributeLocation.Module;
case "type":
return AttributeLocation.Type;
case "return":
return AttributeLocation.Return;
case "method":
return AttributeLocation.Method;
case "field":
return AttributeLocation.Field;
case "event":
return AttributeLocation.Event;
case "param":
return AttributeLocation.Parameter;
case "property":
return AttributeLocation.Property;
case "typevar":
return AttributeLocation.TypeParameter;
default:
return AttributeLocation.None;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
[Flags]
internal enum AttributeLocation : short
{
None = 0,
// the order of these determine the order in which they are displayed in error messages when multiple locations are possible:
Assembly = 1 << 0,
Module = 1 << 1,
Type = 1 << 2,
Method = 1 << 3,
Field = 1 << 4,
Property = 1 << 5,
Event = 1 << 6,
Parameter = 1 << 7,
Return = 1 << 8,
TypeParameter = 1 << 9,
// must be the last:
Unknown = 1 << 10,
}
internal static class AttributeLocationExtensions
{
internal static string ToDisplayString(this AttributeLocation locations)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i < (int)AttributeLocation.Unknown; i <<= 1)
{
if ((locations & (AttributeLocation)i) != 0)
{
if (result.Length > 0)
{
result.Append(", ");
}
switch ((AttributeLocation)i)
{
case AttributeLocation.Assembly:
result.Append("assembly");
break;
case AttributeLocation.Module:
result.Append("module");
break;
case AttributeLocation.Type:
result.Append("type");
break;
case AttributeLocation.Method:
result.Append("method");
break;
case AttributeLocation.Field:
result.Append("field");
break;
case AttributeLocation.Property:
result.Append("property");
break;
case AttributeLocation.Event:
result.Append("event");
break;
case AttributeLocation.Return:
result.Append("return");
break;
case AttributeLocation.Parameter:
result.Append("param");
break;
case AttributeLocation.TypeParameter:
result.Append("typevar");
break;
default:
throw ExceptionUtilities.UnexpectedValue(i);
}
}
}
return result.ToString();
}
internal static AttributeLocation ToAttributeLocation(this SyntaxToken token)
{
// NOTE: to match dev10, we're using the value text, rather
// than the actual text. For example, "@return" is equivalent
// to "return".
return ToAttributeLocation(token.ValueText);
}
internal static AttributeLocation ToAttributeLocation(this Syntax.InternalSyntax.SyntaxToken token)
{
// NOTE: to match dev10, we're using the value text, rather
// than the actual text. For example, "@return" is equivalent
// to "return".
return ToAttributeLocation(token.ValueText);
}
private static AttributeLocation ToAttributeLocation(string text)
{
switch (text)
{
case "assembly":
return AttributeLocation.Assembly;
case "module":
return AttributeLocation.Module;
case "type":
return AttributeLocation.Type;
case "return":
return AttributeLocation.Return;
case "method":
return AttributeLocation.Method;
case "field":
return AttributeLocation.Field;
case "event":
return AttributeLocation.Event;
case "param":
return AttributeLocation.Parameter;
case "property":
return AttributeLocation.Property;
case "typevar":
return AttributeLocation.TypeParameter;
default:
return AttributeLocation.None;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/ExtractMethod/OperationStatus_Statics.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal partial class OperationStatus
{
public static readonly OperationStatus Succeeded = new(OperationStatusFlag.Succeeded, reason: null);
public static readonly OperationStatus FailedWithUnknownReason = new(OperationStatusFlag.None, reason: FeaturesResources.Unknown_error_occurred);
public static readonly OperationStatus OverlapsHiddenPosition = new(OperationStatusFlag.None, FeaturesResources.generated_code_is_overlapping_with_hidden_portion_of_the_code);
public static readonly OperationStatus NoValidLocationToInsertMethodCall = new(OperationStatusFlag.None, FeaturesResources.No_valid_location_to_insert_method_call);
public static readonly OperationStatus NoActiveStatement = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_no_active_statement);
public static readonly OperationStatus ErrorOrUnknownType = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_an_error_or_unknown_type);
public static readonly OperationStatus UnsafeAddressTaken = new(OperationStatusFlag.BestEffort, FeaturesResources.The_address_of_a_variable_is_used_inside_the_selected_code);
public static readonly OperationStatus LocalFunctionCallWithoutDeclaration = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_a_local_function_call_without_its_declaration);
/// <summary>
/// create operation status with the given data
/// </summary>
public static OperationStatus<T> Create<T>(OperationStatus status, T data)
=> new(status, data);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal partial class OperationStatus
{
public static readonly OperationStatus Succeeded = new(OperationStatusFlag.Succeeded, reason: null);
public static readonly OperationStatus FailedWithUnknownReason = new(OperationStatusFlag.None, reason: FeaturesResources.Unknown_error_occurred);
public static readonly OperationStatus OverlapsHiddenPosition = new(OperationStatusFlag.None, FeaturesResources.generated_code_is_overlapping_with_hidden_portion_of_the_code);
public static readonly OperationStatus NoValidLocationToInsertMethodCall = new(OperationStatusFlag.None, FeaturesResources.No_valid_location_to_insert_method_call);
public static readonly OperationStatus NoActiveStatement = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_no_active_statement);
public static readonly OperationStatus ErrorOrUnknownType = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_an_error_or_unknown_type);
public static readonly OperationStatus UnsafeAddressTaken = new(OperationStatusFlag.BestEffort, FeaturesResources.The_address_of_a_variable_is_used_inside_the_selected_code);
public static readonly OperationStatus LocalFunctionCallWithoutDeclaration = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_a_local_function_call_without_its_declaration);
/// <summary>
/// create operation status with the given data
/// </summary>
public static OperationStatus<T> Create<T>(OperationStatus status, T data)
=> new(status, data);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/CodeRefactorings/WorkspaceServices/ISymbolRenamedCodeActionOperationFactoryWorkspaceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Host;
namespace Microsoft.CodeAnalysis.CodeActions.WorkspaceServices
{
internal interface ISymbolRenamedCodeActionOperationFactoryWorkspaceService : IWorkspaceService
{
CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Host;
namespace Microsoft.CodeAnalysis.CodeActions.WorkspaceServices
{
internal interface ISymbolRenamedCodeActionOperationFactoryWorkspaceService : IWorkspaceService
{
CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/NotImplementedMetadataException.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class NotImplementedMetadataException : Exception
{
internal NotImplementedMetadataException(NotImplementedException inner) : base(string.Empty, inner)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class NotImplementedMetadataException : Exception
{
internal NotImplementedMetadataException(NotImplementedException inner) : base(string.Empty, inner)
{
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.GenerateDefaultConstructorItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem, IEquatable<GenerateDefaultConstructor>
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
public override bool Equals(object? obj)
=> Equals(obj as GenerateDefaultConstructor);
public bool Equals(GenerateDefaultConstructor? other)
=> base.Equals(other);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem, IEquatable<GenerateDefaultConstructor>
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
public override bool Equals(object? obj)
=> Equals(obj as GenerateDefaultConstructor);
public bool Equals(GenerateDefaultConstructor? other)
=> base.Equals(other);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/Preview/PreviewUpdater.PreviewDialogWorkspace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
using Workspace = Microsoft.CodeAnalysis.Workspace;
internal partial class PreviewUpdater
{
// internal for testing
internal class PreviewDialogWorkspace : PreviewWorkspace
{
public PreviewDialogWorkspace(Solution solution) : base(solution)
{
}
public void CloseDocument(TextDocument document, SourceText text)
{
switch (document.Kind)
{
case TextDocumentKind.Document:
OnDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
case TextDocumentKind.AnalyzerConfigDocument:
OnAnalyzerConfigDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
case TextDocumentKind.AdditionalDocument:
OnAdditionalDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
default:
throw ExceptionUtilities.UnexpectedValue(document.Kind);
}
}
private class PreviewTextLoader : TextLoader
{
private readonly SourceText _text;
internal PreviewTextLoader(SourceText documentText)
=> _text = documentText;
public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
=> Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken));
internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
=> TextAndVersion.Create(_text, VersionStamp.Create());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
using Workspace = Microsoft.CodeAnalysis.Workspace;
internal partial class PreviewUpdater
{
// internal for testing
internal class PreviewDialogWorkspace : PreviewWorkspace
{
public PreviewDialogWorkspace(Solution solution) : base(solution)
{
}
public void CloseDocument(TextDocument document, SourceText text)
{
switch (document.Kind)
{
case TextDocumentKind.Document:
OnDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
case TextDocumentKind.AnalyzerConfigDocument:
OnAnalyzerConfigDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
case TextDocumentKind.AdditionalDocument:
OnAdditionalDocumentClosed(document.Id, new PreviewTextLoader(text));
break;
default:
throw ExceptionUtilities.UnexpectedValue(document.Kind);
}
}
private class PreviewTextLoader : TextLoader
{
private readonly SourceText _text;
internal PreviewTextLoader(SourceText documentText)
=> _text = documentText;
public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
=> Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken));
internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
=> TextAndVersion.Create(_text, VersionStamp.Create());
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
{
[UseExportProvider]
public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
internal abstract Type GetSignatureHelpProviderType();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
/// <summary>
/// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |].
/// </summary>
/// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |]
/// denoting the expected sighelp span</param>
/// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param>
/// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp.
/// If false, invokes sighelp explicitly at the cursor location.</param>
/// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param>
protected virtual async Task TestAsync(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false,
SourceCodeKind? sourceCodeKind = null,
bool experimental = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await TestSignatureHelpWorkerAsync(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
else
{
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
private async Task TestSignatureHelpWorkerAsync(
string markupWithPositionAndOptSpan,
SourceCodeKind sourceCodeKind,
bool experimental,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings();
TextSpan? textSpan = null;
MarkupTestFile.GetPositionAndSpans(
markupWithPositionAndOptSpan,
out var code,
out var cursorPosition,
out ImmutableArray<TextSpan> textSpans);
if (textSpans.Any())
{
textSpan = textSpans.First();
}
var parseOptions = CreateExperimentalParseOptions();
// regular
var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
if (experimental)
{
document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document1, cursorPosition))
{
var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false);
if (experimental)
{
document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
protected abstract ParseOptions CreateExperimentalParseOptions();
private static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.GetLanguageService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
{
Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
}
foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
{
Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
}
}
protected virtual async Task VerifyCurrentParameterNameAsync(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, sourceCodeKind.Value);
}
else
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Regular);
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Script);
}
}
private static async Task<SignatureHelpState> GetArgumentStateAsync(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo)
{
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null);
}
private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int cursorPosition);
var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
_ = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
}
private static void CompareAndAssertCollectionsAndCurrentParameter(
IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems)
{
Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count());
for (var i = 0; i < expectedTestItems.Count(); i++)
{
CompareSigHelpItemsAndCurrentPosition(
actualSignatureHelpItems,
actualSignatureHelpItems.Items.ElementAt(i),
expectedTestItems.ElementAt(i));
}
}
private static void CompareSigHelpItemsAndCurrentPosition(
SignatureHelpItems items,
SignatureHelpItem actualSignatureHelpItem,
SignatureHelpTestItem expectedTestItem)
{
var currentParameterIndex = -1;
if (expectedTestItem.CurrentParameterIndex != null)
{
if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length)
{
currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value;
}
}
var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex);
// We're a match if the signature matches...
// We're now combining the signature and documentation to make classification work.
if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation))
{
Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content);
}
else
{
Assert.Equal(expectedTestItem.Signature, signature.Content);
}
if (expectedTestItem.PrettyPrintedSignature != null)
{
Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent);
}
if (expectedTestItem.MethodDocumentation != null)
{
Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText());
}
if (expectedTestItem.ParameterDocumentation != null)
{
Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation);
}
if (expectedTestItem.CurrentParameterIndex != null)
{
Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex);
}
if (expectedTestItem.Description != null)
{
Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts));
}
// Always get and realise the classified spans, even if no expected spans are passed in, to at least validate that
// exceptions aren't thrown
var classifiedSpans = actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).ToClassifiedSpans().ToList();
if (expectedTestItem.ClassificationTypeNames is { } classificationTypeNames)
{
Assert.Equal(string.Join(", ", classificationTypeNames), string.Join(", ", classifiedSpans.Select(s => s.ClassificationType)));
}
}
private static string ToString(IEnumerable<TaggedText> list)
=> string.Concat(list.Select(i => i.ToString()));
protected async Task TestSignatureHelpInEditorBrowsableContextsAsync(
string markup,
string referencedCode,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null)
{
AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null.");
}
await TestSignatureHelpWithMetadataReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await TestSignatureHelpWithProjectReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestSignatureHelpInSameProjectHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
{
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
testWorkspace.TryApplyChanges(testWorkspace.CurrentSolution.WithOptions(testWorkspace.Options
.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)));
document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
private async Task TestSignatureHelpWorkerSharedAsync(
TestWorkspace workspace,
string code,
int cursorPosition,
Document document,
TextSpan? textSpan,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspace.ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
if (usePreviousCharAsTrigger)
{
triggerInfo = new SignatureHelpTriggerInfo(
SignatureHelpTriggerReason.TypeCharCommand,
code.ElementAt(cursorPosition - 1));
if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return;
}
}
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
// If we're expecting 0 items, then there's no need to compare them
if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null)
{
return;
}
AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?");
// Verify the span
if (textSpan != null)
{
Assert.Equal(textSpan, items.ApplicableSpan);
}
if (expectedOrderedItemsOrNull != null)
{
CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items);
CompareSelectedIndex(expectedOrderedItemsOrNull, items.SelectedItemIndex);
}
}
private static void CompareSelectedIndex(IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull, int? selectedItemIndex)
{
if (expectedOrderedItemsOrNull == null ||
!expectedOrderedItemsOrNull.Any(i => i.IsSelected))
{
return;
}
Assert.True(expectedOrderedItemsOrNull.Count(i => i.IsSelected) == 1, "Only one expected item can be marked with 'IsSelected'");
Assert.True(selectedItemIndex != null, "Expected an item to be selected, but no item was actually selected");
var counter = 0;
foreach (var item in expectedOrderedItemsOrNull)
{
if (item.IsSelected)
{
Assert.True(selectedItemIndex == counter,
$"Expected item with index {counter} to be selected, but the actual selected index is {selectedItemIndex}.");
}
else
{
Assert.True(selectedItemIndex != counter,
$"Found unexpected selected item. Actual selected index is {selectedItemIndex}.");
}
counter++;
}
}
protected async Task TestSignatureHelpWithMscorlib45Async(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
{
[UseExportProvider]
public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
internal abstract Type GetSignatureHelpProviderType();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
/// <summary>
/// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |].
/// </summary>
/// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |]
/// denoting the expected sighelp span</param>
/// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param>
/// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp.
/// If false, invokes sighelp explicitly at the cursor location.</param>
/// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param>
protected virtual async Task TestAsync(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false,
SourceCodeKind? sourceCodeKind = null,
bool experimental = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await TestSignatureHelpWorkerAsync(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
else
{
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
private async Task TestSignatureHelpWorkerAsync(
string markupWithPositionAndOptSpan,
SourceCodeKind sourceCodeKind,
bool experimental,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings();
TextSpan? textSpan = null;
MarkupTestFile.GetPositionAndSpans(
markupWithPositionAndOptSpan,
out var code,
out var cursorPosition,
out ImmutableArray<TextSpan> textSpans);
if (textSpans.Any())
{
textSpan = textSpans.First();
}
var parseOptions = CreateExperimentalParseOptions();
// regular
var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
if (experimental)
{
document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document1, cursorPosition))
{
var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false);
if (experimental)
{
document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
protected abstract ParseOptions CreateExperimentalParseOptions();
private static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.GetLanguageService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
{
Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
}
foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
{
Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
}
}
protected virtual async Task VerifyCurrentParameterNameAsync(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, sourceCodeKind.Value);
}
else
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Regular);
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Script);
}
}
private static async Task<SignatureHelpState> GetArgumentStateAsync(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo)
{
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null);
}
private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int cursorPosition);
var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
_ = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
}
private static void CompareAndAssertCollectionsAndCurrentParameter(
IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems)
{
Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count());
for (var i = 0; i < expectedTestItems.Count(); i++)
{
CompareSigHelpItemsAndCurrentPosition(
actualSignatureHelpItems,
actualSignatureHelpItems.Items.ElementAt(i),
expectedTestItems.ElementAt(i));
}
}
private static void CompareSigHelpItemsAndCurrentPosition(
SignatureHelpItems items,
SignatureHelpItem actualSignatureHelpItem,
SignatureHelpTestItem expectedTestItem)
{
var currentParameterIndex = -1;
if (expectedTestItem.CurrentParameterIndex != null)
{
if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length)
{
currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value;
}
}
var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex);
// We're a match if the signature matches...
// We're now combining the signature and documentation to make classification work.
if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation))
{
Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content);
}
else
{
Assert.Equal(expectedTestItem.Signature, signature.Content);
}
if (expectedTestItem.PrettyPrintedSignature != null)
{
Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent);
}
if (expectedTestItem.MethodDocumentation != null)
{
Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText());
}
if (expectedTestItem.ParameterDocumentation != null)
{
Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation);
}
if (expectedTestItem.CurrentParameterIndex != null)
{
Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex);
}
if (expectedTestItem.Description != null)
{
Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts));
}
// Always get and realise the classified spans, even if no expected spans are passed in, to at least validate that
// exceptions aren't thrown
var classifiedSpans = actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).ToClassifiedSpans().ToList();
if (expectedTestItem.ClassificationTypeNames is { } classificationTypeNames)
{
Assert.Equal(string.Join(", ", classificationTypeNames), string.Join(", ", classifiedSpans.Select(s => s.ClassificationType)));
}
}
private static string ToString(IEnumerable<TaggedText> list)
=> string.Concat(list.Select(i => i.ToString()));
protected async Task TestSignatureHelpInEditorBrowsableContextsAsync(
string markup,
string referencedCode,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null)
{
AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null.");
}
await TestSignatureHelpWithMetadataReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await TestSignatureHelpWithProjectReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestSignatureHelpInSameProjectHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
{
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
testWorkspace.TryApplyChanges(testWorkspace.CurrentSolution.WithOptions(testWorkspace.Options
.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)));
document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
private async Task TestSignatureHelpWorkerSharedAsync(
TestWorkspace workspace,
string code,
int cursorPosition,
Document document,
TextSpan? textSpan,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspace.ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
if (usePreviousCharAsTrigger)
{
triggerInfo = new SignatureHelpTriggerInfo(
SignatureHelpTriggerReason.TypeCharCommand,
code.ElementAt(cursorPosition - 1));
if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return;
}
}
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
// If we're expecting 0 items, then there's no need to compare them
if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null)
{
return;
}
AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?");
// Verify the span
if (textSpan != null)
{
Assert.Equal(textSpan, items.ApplicableSpan);
}
if (expectedOrderedItemsOrNull != null)
{
CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items);
CompareSelectedIndex(expectedOrderedItemsOrNull, items.SelectedItemIndex);
}
}
private static void CompareSelectedIndex(IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull, int? selectedItemIndex)
{
if (expectedOrderedItemsOrNull == null ||
!expectedOrderedItemsOrNull.Any(i => i.IsSelected))
{
return;
}
Assert.True(expectedOrderedItemsOrNull.Count(i => i.IsSelected) == 1, "Only one expected item can be marked with 'IsSelected'");
Assert.True(selectedItemIndex != null, "Expected an item to be selected, but no item was actually selected");
var counter = 0;
foreach (var item in expectedOrderedItemsOrNull)
{
if (item.IsSelected)
{
Assert.True(selectedItemIndex == counter,
$"Expected item with index {counter} to be selected, but the actual selected index is {selectedItemIndex}.");
}
else
{
Assert.True(selectedItemIndex != counter,
$"Found unexpected selected item. Actual selected index is {selectedItemIndex}.");
}
counter++;
}
}
protected async Task TestSignatureHelpWithMscorlib45Async(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/IGenerateParameterizedMemberService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal interface IGenerateParameterizedMemberService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GenerateMethodAsync(Document document, SyntaxNode node, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal interface IGenerateParameterizedMemberService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GenerateMethodAsync(Document document, SyntaxNode node, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/CSharpTest/Structure/ConstructorDeclarationStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class ConstructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<ConstructorDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new ConstructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor1()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor2()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
} |}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor3()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor4()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|} /* .ctor */
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor5()
{
const string code = @"
class C
{
{|hint:$$public C() // .ctor{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor6()
{
const string code = @"
class C
{
{|hint:$$public C() /* .ctor */{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor7()
{
const string code = @"
class C
{
{|hint:$$public C()
// .ctor{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor8()
{
const string code = @"
class C
{
{|hint:$$public C()
/* .ctor */{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor9()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
public C()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor10()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
public C(int x)
{
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructorWithComments()
{
const string code = @"
class C
{
{|span1:// Goo
// Bar|}
{|hint2:$$public C(){|textspan2:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("span1", "// Goo ...", autoCollapse: true),
Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructorMissingCloseParenAndBody()
{
// Expected behavior is that the class should be outlined, but the constructor should not.
const string code = @"
class C
{
$$C(
}";
await VerifyNoBlockSpansAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class ConstructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<ConstructorDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new ConstructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor1()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor2()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
} |}|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor3()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor4()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|} /* .ctor */
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor5()
{
const string code = @"
class C
{
{|hint:$$public C() // .ctor{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor6()
{
const string code = @"
class C
{
{|hint:$$public C() /* .ctor */{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor7()
{
const string code = @"
class C
{
{|hint:$$public C()
// .ctor{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor8()
{
const string code = @"
class C
{
{|hint:$$public C()
/* .ctor */{|textspan:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor9()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
public C()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructor10()
{
const string code = @"
class C
{
{|hint:$$public C(){|textspan:
{
}|}|}
public C(int x)
{
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructorWithComments()
{
const string code = @"
class C
{
{|span1:// Goo
// Bar|}
{|hint2:$$public C(){|textspan2:
{
}|}|} // .ctor
}";
await VerifyBlockSpansAsync(code,
Region("span1", "// Goo ...", autoCollapse: true),
Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestConstructorMissingCloseParenAndBody()
{
// Expected behavior is that the class should be outlined, but the constructor should not.
const string code = @"
class C
{
$$C(
}";
await VerifyNoBlockSpansAsync(code);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/DebuggerIntelliSense/DebuggerIntellisenseHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal static class DebuggerIntelliSenseHelpers
{
public static ITrackingSpan CreateTrackingSpanFromIndexToEnd(this ITextSnapshot textSnapshot, int index, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(index, textSnapshot.Length), trackingMode);
public static ITrackingSpan CreateTrackingSpanFromStartToIndex(this ITextSnapshot textSnapshot, int index, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(0, index), trackingMode);
public static ITrackingSpan CreateFullTrackingSpan(this ITextSnapshot textSnapshot, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(0, textSnapshot.Length), trackingMode);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal static class DebuggerIntelliSenseHelpers
{
public static ITrackingSpan CreateTrackingSpanFromIndexToEnd(this ITextSnapshot textSnapshot, int index, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(index, textSnapshot.Length), trackingMode);
public static ITrackingSpan CreateTrackingSpanFromStartToIndex(this ITextSnapshot textSnapshot, int index, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(0, index), trackingMode);
public static ITrackingSpan CreateFullTrackingSpan(this ITextSnapshot textSnapshot, SpanTrackingMode trackingMode)
=> textSnapshot.CreateTrackingSpan(Span.FromBounds(0, textSnapshot.Length), trackingMode);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/RQName/ParenthesesTreeWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName
{
internal static class ParenthesesTreeWriter
{
public static string ToParenthesesFormat(SimpleTreeNode tree)
{
var sb = new StringBuilder();
WriteNode(tree, sb);
return sb.ToString();
}
private static void WriteNode(SimpleTreeNode node, StringBuilder sb)
{
sb.Append(node.Text);
if (node is SimpleGroupNode group)
{
sb.Append('(');
for (var i = 0; i < group.Count; i++)
{
if (i > 0)
{
sb.Append(',');
}
WriteNode(group[i], sb);
}
sb.Append(')');
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName
{
internal static class ParenthesesTreeWriter
{
public static string ToParenthesesFormat(SimpleTreeNode tree)
{
var sb = new StringBuilder();
WriteNode(tree, sb);
return sb.ToString();
}
private static void WriteNode(SimpleTreeNode node, StringBuilder sb)
{
sb.Append(node.Text);
if (node is SimpleGroupNode group)
{
sb.Append('(');
for (var i = 0; i < group.Count; i++)
{
if (i > 0)
{
sb.Append(',');
}
WriteNode(group[i], sb);
}
sb.Append(')');
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/IncrementalCaches/SymbolTreeInfoCacheService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
namespace Microsoft.CodeAnalysis.IncrementalCaches
{
internal partial class SymbolTreeInfoIncrementalAnalyzerProvider
{
private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService
{
// Shared with SymbolTreeInfoIncrementalAnalyzer. They populate these values, we read from them.
private readonly ConcurrentDictionary<ProjectId, SymbolTreeInfo> _projectIdToInfo;
private readonly ConcurrentDictionary<MetadataId, MetadataInfo> _metadataIdToInfo;
public SymbolTreeInfoCacheService(
ConcurrentDictionary<ProjectId, SymbolTreeInfo> projectIdToInfo,
ConcurrentDictionary<MetadataId, MetadataInfo> metadataIdToInfo)
{
_projectIdToInfo = projectIdToInfo;
_metadataIdToInfo = metadataIdToInfo;
}
public async ValueTask<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync(
Solution solution,
PortableExecutableReference reference,
CancellationToken cancellationToken)
{
var metadataId = SymbolTreeInfo.GetMetadataIdNoThrow(reference);
if (metadataId == null)
return null;
var checksum = SymbolTreeInfo.GetMetadataChecksum(solution, reference, cancellationToken);
// See if the last value produced matches what the caller is asking for. If so, return that.
if (_metadataIdToInfo.TryGetValue(metadataId, out var metadataInfo) &&
metadataInfo.SymbolTreeInfo.Checksum == checksum)
{
return metadataInfo.SymbolTreeInfo;
}
// If we didn't have it in our cache, see if we can load it from disk.
// Note: pass 'loadOnly' so we only attempt to load from disk, not to actually
// try to create the metadata.
var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync(
solution, reference, checksum, loadOnly: true, cancellationToken).ConfigureAwait(false);
return info;
}
public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync(
Project project, CancellationToken cancellationToken)
{
// See if the last value produced matches what the caller is asking for. If so, return that.
var checksum = await SymbolTreeInfo.GetSourceSymbolsChecksumAsync(project, cancellationToken).ConfigureAwait(false);
if (_projectIdToInfo.TryGetValue(project.Id, out var projectInfo) &&
projectInfo.Checksum == checksum)
{
return projectInfo;
}
// If we didn't have it in our cache, see if we can load it from disk.
// Note: pass 'loadOnly' so we only attempt to load from disk, not to actually
// try to create the index.
var info = await SymbolTreeInfo.GetInfoForSourceAssemblyAsync(
project, checksum, loadOnly: true, cancellationToken).ConfigureAwait(false);
return info;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
namespace Microsoft.CodeAnalysis.IncrementalCaches
{
internal partial class SymbolTreeInfoIncrementalAnalyzerProvider
{
private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService
{
// Shared with SymbolTreeInfoIncrementalAnalyzer. They populate these values, we read from them.
private readonly ConcurrentDictionary<ProjectId, SymbolTreeInfo> _projectIdToInfo;
private readonly ConcurrentDictionary<MetadataId, MetadataInfo> _metadataIdToInfo;
public SymbolTreeInfoCacheService(
ConcurrentDictionary<ProjectId, SymbolTreeInfo> projectIdToInfo,
ConcurrentDictionary<MetadataId, MetadataInfo> metadataIdToInfo)
{
_projectIdToInfo = projectIdToInfo;
_metadataIdToInfo = metadataIdToInfo;
}
public async ValueTask<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync(
Solution solution,
PortableExecutableReference reference,
CancellationToken cancellationToken)
{
var metadataId = SymbolTreeInfo.GetMetadataIdNoThrow(reference);
if (metadataId == null)
return null;
var checksum = SymbolTreeInfo.GetMetadataChecksum(solution, reference, cancellationToken);
// See if the last value produced matches what the caller is asking for. If so, return that.
if (_metadataIdToInfo.TryGetValue(metadataId, out var metadataInfo) &&
metadataInfo.SymbolTreeInfo.Checksum == checksum)
{
return metadataInfo.SymbolTreeInfo;
}
// If we didn't have it in our cache, see if we can load it from disk.
// Note: pass 'loadOnly' so we only attempt to load from disk, not to actually
// try to create the metadata.
var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync(
solution, reference, checksum, loadOnly: true, cancellationToken).ConfigureAwait(false);
return info;
}
public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync(
Project project, CancellationToken cancellationToken)
{
// See if the last value produced matches what the caller is asking for. If so, return that.
var checksum = await SymbolTreeInfo.GetSourceSymbolsChecksumAsync(project, cancellationToken).ConfigureAwait(false);
if (_projectIdToInfo.TryGetValue(project.Id, out var projectInfo) &&
projectInfo.Checksum == checksum)
{
return projectInfo;
}
// If we didn't have it in our cache, see if we can load it from disk.
// Note: pass 'loadOnly' so we only attempt to load from disk, not to actually
// try to create the index.
var info = await SymbolTreeInfo.GetInfoForSourceAssemblyAsync(
project, checksum, loadOnly: true, cancellationToken).ConfigureAwait(false);
return info;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/Core.Wpf/InlineRename/Taggers/ClassificationFormatDefinitions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal sealed class ClassificationFormatDefinitions
{
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.InlineRenameField)]
[Name(ClassificationTypeDefinitions.InlineRenameField)]
[Order(After = Priority.High)]
[UserVisible(true)]
private class InlineRenameFieldFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InlineRenameFieldFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Text;
this.ForegroundColor = Color.FromRgb(0x00, 0x64, 0x00);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal sealed class ClassificationFormatDefinitions
{
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.InlineRenameField)]
[Name(ClassificationTypeDefinitions.InlineRenameField)]
[Order(After = Priority.High)]
[UserVisible(true)]
private class InlineRenameFieldFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InlineRenameFieldFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Text;
this.ForegroundColor = Color.FromRgb(0x00, 0x64, 0x00);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/VisualBasic/BasicAnalyzerDriver/BasicAnalyzerDriver.shproj | <?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>
<PropertyGroup Label="Globals">
<ProjectGuid>e8f0baa5-7327-43d1-9a51-644e81ae55f1</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<ExcludeFromSourceBuild>true</ExcludeFromSourceBuild>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="BasicAnalyzerDriver.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.VisualBasic.targets" />
</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>
<PropertyGroup Label="Globals">
<ProjectGuid>e8f0baa5-7327-43d1-9a51-644e81ae55f1</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<ExcludeFromSourceBuild>true</ExcludeFromSourceBuild>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="BasicAnalyzerDriver.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.VisualBasic.targets" />
</Project>
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/CodeFixes/FirstDiagnosticResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal readonly struct FirstDiagnosticResult
{
public readonly bool PartialResult;
public readonly bool HasFix;
public readonly DiagnosticData Diagnostic;
public FirstDiagnosticResult(bool partialResult, bool hasFix, DiagnosticData diagnostic)
{
PartialResult = partialResult;
HasFix = hasFix;
Diagnostic = diagnostic;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal readonly struct FirstDiagnosticResult
{
public readonly bool PartialResult;
public readonly bool HasFix;
public readonly DiagnosticData Diagnostic;
public FirstDiagnosticResult(bool partialResult, bool hasFix, DiagnosticData diagnostic)
{
PartialResult = partialResult;
HasFix = hasFix;
Diagnostic = diagnostic;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/CSharp/Portable/Errors/LazyArrayElementCantBeRefAnyDiagnosticInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class LazyArrayElementCantBeRefAnyDiagnosticInfo : LazyDiagnosticInfo
{
private readonly TypeWithAnnotations _possiblyRestrictedTypeSymbol;
internal LazyArrayElementCantBeRefAnyDiagnosticInfo(TypeWithAnnotations possiblyRestrictedTypeSymbol)
{
_possiblyRestrictedTypeSymbol = possiblyRestrictedTypeSymbol;
}
protected override DiagnosticInfo ResolveInfo()
{
if (_possiblyRestrictedTypeSymbol.IsRestrictedType())
{
return new CSDiagnosticInfo(ErrorCode.ERR_ArrayElementCantBeRefAny, _possiblyRestrictedTypeSymbol.Type);
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class LazyArrayElementCantBeRefAnyDiagnosticInfo : LazyDiagnosticInfo
{
private readonly TypeWithAnnotations _possiblyRestrictedTypeSymbol;
internal LazyArrayElementCantBeRefAnyDiagnosticInfo(TypeWithAnnotations possiblyRestrictedTypeSymbol)
{
_possiblyRestrictedTypeSymbol = possiblyRestrictedTypeSymbol;
}
protected override DiagnosticInfo ResolveInfo()
{
if (_possiblyRestrictedTypeSymbol.IsRestrictedType())
{
return new CSDiagnosticInfo(ErrorCode.ERR_ArrayElementCantBeRefAny, _possiblyRestrictedTypeSymbol.Type);
}
return null;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingUsingsOnPaste.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest
{
public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste))
{
}
protected override string LanguageName => LanguageNames.CSharp;
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabled()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabledWithNull()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null);
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyAddImportsOnPaste()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest
{
public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste))
{
}
protected override string LanguageName => LanguageNames.CSharp;
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabled()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabledWithNull()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null);
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyAddImportsOnPaste()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste");
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/CSharpTest/CodeActions/ConvertIfToSwitch/ConvertIfToSwitchTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch.CSharpConvertIfToSwitchCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertIfToSwitch
{
public class ConvertIfToSwitchTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestUnreachableEndPoint()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || i == 2 || i == 3)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestReachableEndPoint()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || i == 2 || i == 3)
M(i);
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
M(i);
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnSubsequentBlock()
{
var code = @"class C
{
int M(int i)
{
$$if (i == 3) return 0;
{ if (i == 6) return 1; }
return 2;
}
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestElseBlock_01()
{
var source =
@"class C
{
int {|#0:M|}(int i)
{
$$if (i == 3) return 0;
else { if (i == 6) return 1; }
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int i)
{
switch (i)
{
case 3:
return 0;
case 6:
return 1;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int)"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int)"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestElseBlock_02()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 3)
{
return 0;
}
else
{
if (i == 6) return 1;
if (i == 7) return 1;
return 0;
}
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 3:
return 0;
case 6:
return 1;
case 7:
return 1;
default:
return 0;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_01()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || 2 == i || i == 3) M(0);
else if (i == 4 || 5 == i || i == 6) M(1);
else M(2);
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
M(0);
break;
case 4:
case 5:
case 6:
M(1);
break;
default:
M(2);
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_02_CSharp8()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 0) M(0);
else if (o is int i && i > 0) M(1);
else return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 0:
M(0);
break;
case int i when i > 0:
M(1);
break;
default:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_02_CSharp9()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 0) M(0);
else if (o is int i && i > 0) M(1);
else return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 0:
M(0);
break;
case int i when i > 0:
M(1);
break;
default:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestExpressionOrder()
{
var source =
@"class C
{
void M(int i)
{
$$if (1 == i || i == 2 || 3 == i)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestConstantExpression()
{
var source =
@"class C
{
void M(int i)
{
const int A = 1, B = 2, C = 3;
$$if (A == i || B == i || C == i)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
const int A = 1, B = 2, C = 3;
switch (i)
{
case A:
case B:
case C:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnNonConstantExpression()
{
var source =
@"class C
{
void M(int i)
{
int A = 1, B = 2, C = 3;
$$if (A == i || B == i || C == i)
return;
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnDifferentOperands()
{
var source =
@"class C
{
void M(int i, int j)
{
$$if (i == 5 || 6 == j) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnSingleCase()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 5) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
[CombinatorialData]
public async Task TestIsExpression(
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
var source =
@"class C
{
void M(object o)
{
$$if (o is int || o is string || o is C)
return;
}
}";
var fixedSource = languageVersion switch
{
LanguageVersion.CSharp8 =>
@"class C
{
void M(object o)
{
switch (o)
{
case int _:
case string _:
case C _:
return;
}
}
}",
LanguageVersion.CSharp9 =>
@"class C
{
void M(object o)
{
switch (o)
{
case int:
case string:
case C:
return;
}
}
}",
_ => throw ExceptionUtilities.Unreachable,
};
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = languageVersion,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_01()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is int i)
return;
else if (o is string s)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case int i:
return;
case string s:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_02_CSharp8()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length == 5)
return;
else if (o is int i)
return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length == 5:
return;
case int i:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_02_CSharp9()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length == 5)
return;
else if (o is int i)
return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length == 5:
return;
case int i:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_03()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && (s.Length > 5 && s.Length < 10))
return;
else if (o is int i)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
return;
case int i:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_04()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 5 && s.Length < 10)
return;
else if (o is int i)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
return;
case int i:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexExpression_01()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 5 &&
s.Length < 10)
{
M(o: 0);
}
else if (o is int i)
{
M(o: 0);
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
M(o: 0);
break;
case int i:
M(o: 0);
break;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingIfCaretDoesntIntersectWithTheIfKeyword()
{
var source =
@"class C
{
void M(int i)
{
if $$(i == 3) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestKeepBlockIfThereIsVariableDeclaration()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 3)
{
var x = i;
}
else if (i == 4)
{
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 3:
{
var x = i;
break;
}
case 4:
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnBreak_01()
{
var source =
@"class C
{
void M(int i)
{
while (true)
{
$$if (i == 5) break;
}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnBreak_02()
{
var source =
@"class C
{
void M(int i)
{
while (true)
{
$$if (i == 5) M({|#0:b|}, i);
else break;
}
}
}";
await VerifyCS.VerifyRefactoringAsync(
source,
// /0/Test0.cs(7,27): error CS0103: The name 'b' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(0).WithArguments("b"),
source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestNestedBreak()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1)
{
while (true)
{
break;
}
}
else if (i == 2)
{
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
while (true)
{
break;
}
break;
case 2:
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_01()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
switch (i)
{
case null:
return 5;
case 0:
return 6;
default:
return 7;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSwitchExpression_01()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
return i switch
{
null => 5,
0 => 6,
_ => 7
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSwitchExpression_02()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) { return 5; }
if (i == 0) { return 6; }
else { return 7; }
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
return i switch
{
null => 5,
0 => 6,
_ => 7
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_02()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) {}
if (i == 1) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
switch (i)
{
case null:
return 5;
case 0:
break;
}
if (i == 1) return 6;
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_03()
{
var source =
@"class C
{
int {|#0:M|}(int? i)
{
while (true)
{
$$if (i == null) return 5; else if (i == 1) return 1;
if (i == 0) break;
if (i == 1) return 6;
return 7;
}
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int? i)
{
while (true)
{
switch (i)
{
case null:
return 5;
case 1:
return 1;
}
if (i == 0) break;
if (i == 1) return 6;
return 7;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int?)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int?)"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int?)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int?)"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_04()
{
var source =
@"class C
{
string M(object i)
{
$$if (i == null || i as string == """") return null;
if ((string)i == ""0"") return i as string;
else return i.ToString();
}
}";
var fixedSource =
@"class C
{
string M(object i)
{
switch (i)
{
case null:
case """":
return null;
case ""0"":
return i as string;
default:
return i.ToString();
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_05()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 10) return 5;
if (i == 20) return 6;
if (i == i) return 0;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 10:
return 5;
case 20:
return 6;
}
if (i == i) return 0;
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_06()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 10)
{
return 5;
}
else if (i == 20)
{
return 6;
}
if (i == i)
{
return 0;
}
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 10:
return 5;
case 20:
return 6;
}
if (i == i)
{
return 0;
}
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_07()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 5)
{
return 4;
}
else if (i == 1)
{
return 1;
}
if (i == 10)
{
return 5;
}
else if (i == i)
{
return 6;
}
else
{
return 0;
}
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 5:
return 4;
case 1:
return 1;
}
if (i == 10)
{
return 5;
}
else if (i == i)
{
return 6;
}
else
{
return 0;
}
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21109, "https://github.com/dotnet/roslyn/issues/21109")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTrivia1()
{
var source =
@"class C
{
int {|#0:M|}(int x, int z)
{
#if TRUE
{|#1:Console|}.WriteLine();
#endif
$$if (x == 1)
{
{|#2:Console|}.WriteLine(x + z);
}
else if (x == 2)
{
{|#3:Console|}.WriteLine(x + z);
}
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int x, int z)
{
#if TRUE
{|#1:Console|}.WriteLine();
#endif
switch (x)
{
case 1:
{|#2:Console|}.WriteLine(x + z);
break;
case 2:
{|#3:Console|}.WriteLine(x + z);
break;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int, int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int, int)"),
// /0/Test0.cs(6,9): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(1).WithArguments("Console"),
// /0/Test0.cs(11,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(2).WithArguments("Console"),
// /0/Test0.cs(15,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(3).WithArguments("Console"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int, int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int, int)"),
// /0/Test0.cs(6,9): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(1).WithArguments("Console"),
// /0/Test0.cs(11,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(2).WithArguments("Console"),
// /0/Test0.cs(15,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(3).WithArguments("Console"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21101, "https://github.com/dotnet/roslyn/issues/21101")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTrivia2()
{
var source =
@"class C
{
int M(int i, string[] args)
{
$$if (/* t0 */args.Length /* t1*/ == /* t2 */ 2)
return /* t3 */ 0 /* t4 */; /* t5 */
else /* t6 */
return /* t7 */ 3 /* t8 */;
}
}";
var fixedSource =
@"class C
{
int M(int i, string[] args)
{
switch (/* t0 */args.Length /* t1*/ )
{
case 2:
return /* t3 */ 0 /* t4 */; /* t5 */
default:
return /* t7 */ 3 /* t8 */;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd1_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd1_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd2_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd2_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd3_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd3_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd4()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd4_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd5()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd6()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd7()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd8()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd9()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd10()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2 && i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd11()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd12()
{
var source =
@"class C
{
void M(int i)
{
$$if (((i == 1) && i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd13()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && (i == 2)) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd14()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && (i == 2)) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd15()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && ((i == 2) && i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd16()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2 && (i == 3)))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(37035, "https://github.com/dotnet/roslyn/issues/37035")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexExpression_02()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string text &&
int.TryParse(text, out var n) &&
n < 5 && n > -5)
{
}
else
{
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string text when int.TryParse(text, out var n) && n < 5 && n > -5:
break;
default:
break;
}
}
}");
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestRange_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i && 1 <= i)
{
return;
}
else if (7 >= i && 6 <= i)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestRange_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i && 1 <= i)
{
return;
}
else if (7 >= i && 6 <= i)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case <= 5 and >= 1:
return;
case <= 7 and >= 6:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i || 1 <= i)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i || 1 <= i)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case <= 5:
case >= 1:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_SwitchExpression_CSharp9()
{
var source =
@"class C
{
int M(int i)
{
$$if (5 >= i || 1 <= i)
{
return 1;
}
else
{
return 2;
}
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
return i switch
{
<= 5 or >= 1 => 1,
{|#0:_|} => 2
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(8,13): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
DiagnosticResult.CompilerError("CS8510").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case < 10:
case > 20:
case {|#0:>= 30 and <= 40|}:
case {|#1:50|}:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
// /0/Test0.cs(10,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(1),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_Precedence_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 0 || i is < 10 or > 20 && i is >= 30 or <= 40)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 0:
case (< 10 or > 20) and (>= 30 or <= 40):
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestInequality()
{
var source =
@"class C
{
void M(int i)
{
[||]if ((i > 123 && i < 456) && i != 0 || i == 10)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case > 123 and < 456 when i != 0:
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(44278, "https://github.com/dotnet/roslyn/issues/44278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTopLevelStatement()
{
var source = @"
var e = new ET1();
[||]if (e == ET1.A)
{
}
else if (e == ET1.C)
{
}
enum ET1
{
A,
B,
C,
}";
var fixedSource = @"
var e = new ET1();
switch (e)
{
case ET1.A:
break;
case ET1.C:
break;
}
enum ET1
{
A,
B,
C,
}";
var test = new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.ExpectedDiagnostics.Add(
// /0/Test0.cs(2,1): error CS8805: Program using top-level statements must be an executable.
DiagnosticResult.CompilerError("CS8805").WithSpan(2, 1, 2, 19));
await test.RunAsync();
}
[WorkItem(46863, "https://github.com/dotnet/roslyn/issues/46863")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task CommentsAtTheEndOfBlocksShouldBePlacedBeforeBreakStatements()
{
var source = @"
class C
{
void M(int p)
{
[||]if (p == 1)
{
DoA();
// Comment about why A doesn't need something here
}
else if (p == 2)
{
DoB();
// Comment about why B doesn't need something here
}
}
void DoA() { }
void DoB() { }
}";
var fixedSource = @"
class C
{
void M(int p)
{
switch (p)
{
case 1:
DoA();
// Comment about why A doesn't need something here
break;
case 2:
DoB();
// Comment about why B doesn't need something here
break;
}
}
void DoA() { }
void DoB() { }
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch.CSharpConvertIfToSwitchCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertIfToSwitch
{
public class ConvertIfToSwitchTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestUnreachableEndPoint()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || i == 2 || i == 3)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestReachableEndPoint()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || i == 2 || i == 3)
M(i);
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
M(i);
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnSubsequentBlock()
{
var code = @"class C
{
int M(int i)
{
$$if (i == 3) return 0;
{ if (i == 6) return 1; }
return 2;
}
}";
await VerifyCS.VerifyRefactoringAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestElseBlock_01()
{
var source =
@"class C
{
int {|#0:M|}(int i)
{
$$if (i == 3) return 0;
else { if (i == 6) return 1; }
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int i)
{
switch (i)
{
case 3:
return 0;
case 6:
return 1;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int)"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int)"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestElseBlock_02()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 3)
{
return 0;
}
else
{
if (i == 6) return 1;
if (i == 7) return 1;
return 0;
}
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 3:
return 0;
case 6:
return 1;
case 7:
return 1;
default:
return 0;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_01()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 || 2 == i || i == 3) M(0);
else if (i == 4 || 5 == i || i == 6) M(1);
else M(2);
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
M(0);
break;
case 4:
case 5:
case 6:
M(1);
break;
default:
M(2);
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_02_CSharp8()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 0) M(0);
else if (o is int i && i > 0) M(1);
else return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 0:
M(0);
break;
case int i when i > 0:
M(1);
break;
default:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMultipleCases_02_CSharp9()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 0) M(0);
else if (o is int i && i > 0) M(1);
else return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 0:
M(0);
break;
case int i when i > 0:
M(1);
break;
default:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestExpressionOrder()
{
var source =
@"class C
{
void M(int i)
{
$$if (1 == i || i == 2 || 3 == i)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
case 2:
case 3:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestConstantExpression()
{
var source =
@"class C
{
void M(int i)
{
const int A = 1, B = 2, C = 3;
$$if (A == i || B == i || C == i)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
const int A = 1, B = 2, C = 3;
switch (i)
{
case A:
case B:
case C:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnNonConstantExpression()
{
var source =
@"class C
{
void M(int i)
{
int A = 1, B = 2, C = 3;
$$if (A == i || B == i || C == i)
return;
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnDifferentOperands()
{
var source =
@"class C
{
void M(int i, int j)
{
$$if (i == 5 || 6 == j) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnSingleCase()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 5) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
[CombinatorialData]
public async Task TestIsExpression(
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
var source =
@"class C
{
void M(object o)
{
$$if (o is int || o is string || o is C)
return;
}
}";
var fixedSource = languageVersion switch
{
LanguageVersion.CSharp8 =>
@"class C
{
void M(object o)
{
switch (o)
{
case int _:
case string _:
case C _:
return;
}
}
}",
LanguageVersion.CSharp9 =>
@"class C
{
void M(object o)
{
switch (o)
{
case int:
case string:
case C:
return;
}
}
}",
_ => throw ExceptionUtilities.Unreachable,
};
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = languageVersion,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_01()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is int i)
return;
else if (o is string s)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case int i:
return;
case string s:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_02_CSharp8()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length == 5)
return;
else if (o is int i)
return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length == 5:
return;
case int i:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_02_CSharp9()
{
var source =
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length == 5)
return;
else if (o is int i)
return;
}
}";
var fixedSource =
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length == 5:
return;
case int i:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_03()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && (s.Length > 5 && s.Length < 10))
return;
else if (o is int i)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
return;
case int i:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestIsPatternExpression_04()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 5 && s.Length < 10)
return;
else if (o is int i)
return;
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
return;
case int i:
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexExpression_01()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string s && s.Length > 5 &&
s.Length < 10)
{
M(o: 0);
}
else if (o is int i)
{
M(o: 0);
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string s when s.Length > 5 && s.Length < 10:
M(o: 0);
break;
case int i:
M(o: 0);
break;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingIfCaretDoesntIntersectWithTheIfKeyword()
{
var source =
@"class C
{
void M(int i)
{
if $$(i == 3) {}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestKeepBlockIfThereIsVariableDeclaration()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 3)
{
var x = i;
}
else if (i == 4)
{
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 3:
{
var x = i;
break;
}
case 4:
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnBreak_01()
{
var source =
@"class C
{
void M(int i)
{
while (true)
{
$$if (i == 5) break;
}
}
}";
await VerifyCS.VerifyRefactoringAsync(source, source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestMissingOnBreak_02()
{
var source =
@"class C
{
void M(int i)
{
while (true)
{
$$if (i == 5) M({|#0:b|}, i);
else break;
}
}
}";
await VerifyCS.VerifyRefactoringAsync(
source,
// /0/Test0.cs(7,27): error CS0103: The name 'b' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(0).WithArguments("b"),
source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestNestedBreak()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1)
{
while (true)
{
break;
}
}
else if (i == 2)
{
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1:
while (true)
{
break;
}
break;
case 2:
break;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_01()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
switch (i)
{
case null:
return 5;
case 0:
return 6;
default:
return 7;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSwitchExpression_01()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
return i switch
{
null => 5,
0 => 6,
_ => 7
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSwitchExpression_02()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) { return 5; }
if (i == 0) { return 6; }
else { return 7; }
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
return i switch
{
null => 5,
0 => 6,
_ => 7
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_02()
{
var source =
@"class C
{
int M(int? i)
{
$$if (i == null) return 5;
if (i == 0) {}
if (i == 1) return 6;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int? i)
{
switch (i)
{
case null:
return 5;
case 0:
break;
}
if (i == 1) return 6;
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_03()
{
var source =
@"class C
{
int {|#0:M|}(int? i)
{
while (true)
{
$$if (i == null) return 5; else if (i == 1) return 1;
if (i == 0) break;
if (i == 1) return 6;
return 7;
}
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int? i)
{
while (true)
{
switch (i)
{
case null:
return 5;
case 1:
return 1;
}
if (i == 0) break;
if (i == 1) return 6;
return 7;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int?)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int?)"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int?)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int?)"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_04()
{
var source =
@"class C
{
string M(object i)
{
$$if (i == null || i as string == """") return null;
if ((string)i == ""0"") return i as string;
else return i.ToString();
}
}";
var fixedSource =
@"class C
{
string M(object i)
{
switch (i)
{
case null:
case """":
return null;
case ""0"":
return i as string;
default:
return i.ToString();
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_05()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 10) return 5;
if (i == 20) return 6;
if (i == i) return 0;
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 10:
return 5;
case 20:
return 6;
}
if (i == i) return 0;
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_06()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 10)
{
return 5;
}
else if (i == 20)
{
return 6;
}
if (i == i)
{
return 0;
}
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 10:
return 5;
case 20:
return 6;
}
if (i == i)
{
return 0;
}
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestSubsequentIfStatements_07()
{
var source =
@"class C
{
int M(int i)
{
$$if (i == 5)
{
return 4;
}
else if (i == 1)
{
return 1;
}
if (i == 10)
{
return 5;
}
else if (i == i)
{
return 6;
}
else
{
return 0;
}
return 7;
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
switch (i)
{
case 5:
return 4;
case 1:
return 1;
}
if (i == 10)
{
return 5;
}
else if (i == i)
{
return 6;
}
else
{
return 0;
}
return 7;
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21109, "https://github.com/dotnet/roslyn/issues/21109")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTrivia1()
{
var source =
@"class C
{
int {|#0:M|}(int x, int z)
{
#if TRUE
{|#1:Console|}.WriteLine();
#endif
$$if (x == 1)
{
{|#2:Console|}.WriteLine(x + z);
}
else if (x == 2)
{
{|#3:Console|}.WriteLine(x + z);
}
}
}";
var fixedSource =
@"class C
{
int {|#0:M|}(int x, int z)
{
#if TRUE
{|#1:Console|}.WriteLine();
#endif
switch (x)
{
case 1:
{|#2:Console|}.WriteLine(x + z);
break;
case 2:
{|#3:Console|}.WriteLine(x + z);
break;
}
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources = { source },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int, int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int, int)"),
// /0/Test0.cs(6,9): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(1).WithArguments("Console"),
// /0/Test0.cs(11,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(2).WithArguments("Console"),
// /0/Test0.cs(15,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(3).WithArguments("Console"),
},
},
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(3,9): error CS0161: 'C.M(int, int)': not all code paths return a value
DiagnosticResult.CompilerError("CS0161").WithLocation(0).WithArguments("C.M(int, int)"),
// /0/Test0.cs(6,9): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(1).WithArguments("Console"),
// /0/Test0.cs(11,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(2).WithArguments("Console"),
// /0/Test0.cs(15,13): error CS0103: The name 'Console' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithLocation(3).WithArguments("Console"),
},
},
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21101, "https://github.com/dotnet/roslyn/issues/21101")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTrivia2()
{
var source =
@"class C
{
int M(int i, string[] args)
{
$$if (/* t0 */args.Length /* t1*/ == /* t2 */ 2)
return /* t3 */ 0 /* t4 */; /* t5 */
else /* t6 */
return /* t7 */ 3 /* t8 */;
}
}";
var fixedSource =
@"class C
{
int M(int i, string[] args)
{
switch (/* t0 */args.Length /* t1*/ )
{
case 2:
return /* t3 */ 0 /* t4 */; /* t5 */
default:
return /* t7 */ 3 /* t8 */;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd1_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd1_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd2_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd2_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd3_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd3_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd4()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp8,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd4_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case {|#0:1 and 2 and 3|}:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd5()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd6()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && i == 2 && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd7()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && i == 2 && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd8()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd9()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd10()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 1 && (i == 2 && i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd11()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd12()
{
var source =
@"class C
{
void M(int i)
{
$$if (((i == 1) && i == 2) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd13()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && (i == 2)) && i == 3)
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd14()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1 && (i == 2)) && (i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd15()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && ((i == 2) && i == 3))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(21360, "https://github.com/dotnet/roslyn/issues/21360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestCompoundLogicalAnd16()
{
var source =
@"class C
{
void M(int i)
{
$$if ((i == 1) && (i == 2 && (i == 3)))
return;
else if (i == 10)
return;
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 1 when i == 2 && i == 3:
return;
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(37035, "https://github.com/dotnet/roslyn/issues/37035")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexExpression_02()
{
await VerifyCS.VerifyRefactoringAsync(
@"class C
{
void M(object o)
{
$$if (o is string text &&
int.TryParse(text, out var n) &&
n < 5 && n > -5)
{
}
else
{
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case string text when int.TryParse(text, out var n) && n < 5 && n > -5:
break;
default:
break;
}
}
}");
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestRange_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i && 1 <= i)
{
return;
}
else if (7 >= i && 6 <= i)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestRange_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i && 1 <= i)
{
return;
}
else if (7 >= i && 6 <= i)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case <= 5 and >= 1:
return;
case <= 7 and >= 6:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i || 1 <= i)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (5 >= i || 1 <= i)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case <= 5:
case >= 1:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComparison_SwitchExpression_CSharp9()
{
var source =
@"class C
{
int M(int i)
{
$$if (5 >= i || 1 <= i)
{
return 1;
}
else
{
return 2;
}
}
}";
var fixedSource =
@"class C
{
int M(int i)
{
return i switch
{
<= 5 or >= 1 => 1,
{|#0:_|} => 2
};
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(8,13): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
DiagnosticResult.CompilerError("CS8510").WithLocation(0),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionIndex = 1,
CodeActionEquivalenceKey = "SwitchExpression",
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_CSharp8()
{
var source =
@"class C
{
void M(int i)
{
$$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50)
{
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i < 10 || 20 < i || (i >= 30 && 40 >= i) || i == 50)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case < 10:
case > 20:
case {|#0:>= 30 and <= 40|}:
case {|#1:50|}:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedState =
{
Sources = { fixedSource },
ExpectedDiagnostics =
{
// /0/Test0.cs(9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(0),
// /0/Test0.cs(10,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
DiagnosticResult.CompilerError("CS8120").WithLocation(1),
},
},
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestComplexIf_Precedence_CSharp9()
{
var source =
@"class C
{
void M(int i)
{
$$if (i == 0 || i is < 10 or > 20 && i is >= 30 or <= 40)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case 0:
case (< 10 or > 20) and (>= 30 or <= 40):
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestInequality()
{
var source =
@"class C
{
void M(int i)
{
[||]if ((i > 123 && i < 456) && i != 0 || i == 10)
{
return;
}
}
}";
var fixedSource =
@"class C
{
void M(int i)
{
switch (i)
{
case > 123 and < 456 when i != 0:
case 10:
return;
}
}
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(44278, "https://github.com/dotnet/roslyn/issues/44278")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task TestTopLevelStatement()
{
var source = @"
var e = new ET1();
[||]if (e == ET1.A)
{
}
else if (e == ET1.C)
{
}
enum ET1
{
A,
B,
C,
}";
var fixedSource = @"
var e = new ET1();
switch (e)
{
case ET1.A:
break;
case ET1.C:
break;
}
enum ET1
{
A,
B,
C,
}";
var test = new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
LanguageVersion = LanguageVersion.CSharp9,
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.ExpectedDiagnostics.Add(
// /0/Test0.cs(2,1): error CS8805: Program using top-level statements must be an executable.
DiagnosticResult.CompilerError("CS8805").WithSpan(2, 1, 2, 19));
await test.RunAsync();
}
[WorkItem(46863, "https://github.com/dotnet/roslyn/issues/46863")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)]
public async Task CommentsAtTheEndOfBlocksShouldBePlacedBeforeBreakStatements()
{
var source = @"
class C
{
void M(int p)
{
[||]if (p == 1)
{
DoA();
// Comment about why A doesn't need something here
}
else if (p == 2)
{
DoB();
// Comment about why B doesn't need something here
}
}
void DoA() { }
void DoB() { }
}";
var fixedSource = @"
class C
{
void M(int p)
{
switch (p)
{
case 1:
DoA();
// Comment about why A doesn't need something here
break;
case 2:
DoB();
// Comment about why B doesn't need something here
break;
}
}
void DoA() { }
void DoB() { }
}";
await new VerifyCS.Test
{
TestCode = source,
FixedCode = fixedSource,
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/LanguageServer/ProtocolUnitTests/References/FindImplementationsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References
{
public class FindImplementationsTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestFindImplementationAsync()
{
var markup =
@"interface IA
{
void {|caret:|}M();
}
class A : IA
{
void IA.{|implementation:M|}()
{
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
[Fact]
public async Task TestFindImplementationAsync_DifferentDocument()
{
var markups = new string[]
{
@"namespace One
{
interface IA
{
void {|caret:|}M();
}
}",
@"namespace One
{
class A : IA
{
void IA.{|implementation:M|}()
{
}
}
}"
};
using var testLspServer = CreateTestLspServer(markups, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
[Fact]
public async Task TestFindImplementationAsync_MappedFile()
{
var markup =
@"interface IA
{
void M();
}
class A : IA
{
void IA.M()
{
}
}";
using var testLspServer = CreateTestLspServer(string.Empty, out var _);
AddMappedDocument(testLspServer.TestWorkspace, markup);
var position = new LSP.Position { Line = 2, Character = 9 };
var results = await RunFindImplementationAsync(testLspServer, new LSP.Location
{
Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"),
Range = new LSP.Range { Start = position, End = position }
});
AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results);
}
[Fact]
public async Task TestFindImplementationAsync_InvalidLocation()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
Assert.Empty(results);
}
[Fact, WorkItem(44846, "https://github.com/dotnet/roslyn/issues/44846")]
public async Task TestFindImplementationAsync_MultipleLocations()
{
var markup =
@"class {|caret:|}{|implementation:A|} { }
class {|implementation:B|} : A { }
class {|implementation:C|} : A { }";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
private static async Task<LSP.Location[]> RunFindImplementationAsync(TestLspServer testLspServer, LSP.Location caret)
{
return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentImplementationName,
CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References
{
public class FindImplementationsTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestFindImplementationAsync()
{
var markup =
@"interface IA
{
void {|caret:|}M();
}
class A : IA
{
void IA.{|implementation:M|}()
{
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
[Fact]
public async Task TestFindImplementationAsync_DifferentDocument()
{
var markups = new string[]
{
@"namespace One
{
interface IA
{
void {|caret:|}M();
}
}",
@"namespace One
{
class A : IA
{
void IA.{|implementation:M|}()
{
}
}
}"
};
using var testLspServer = CreateTestLspServer(markups, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
[Fact]
public async Task TestFindImplementationAsync_MappedFile()
{
var markup =
@"interface IA
{
void M();
}
class A : IA
{
void IA.M()
{
}
}";
using var testLspServer = CreateTestLspServer(string.Empty, out var _);
AddMappedDocument(testLspServer.TestWorkspace, markup);
var position = new LSP.Position { Line = 2, Character = 9 };
var results = await RunFindImplementationAsync(testLspServer, new LSP.Location
{
Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"),
Range = new LSP.Range { Start = position, End = position }
});
AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results);
}
[Fact]
public async Task TestFindImplementationAsync_InvalidLocation()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
Assert.Empty(results);
}
[Fact, WorkItem(44846, "https://github.com/dotnet/roslyn/issues/44846")]
public async Task TestFindImplementationAsync_MultipleLocations()
{
var markup =
@"class {|caret:|}{|implementation:A|} { }
class {|implementation:B|} : A { }
class {|implementation:C|} : A { }";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindImplementationAsync(testLspServer, locations["caret"].Single());
AssertLocationsEqual(locations["implementation"], results);
}
private static async Task<LSP.Location[]> RunFindImplementationAsync(TestLspServer testLspServer, LSP.Location caret)
{
return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentImplementationName,
CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None);
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseXml.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports Roslyn.Test.Utilities
Public Class ParseXml
Inherits BasicTestBase
<Fact>
Public Sub ParseElement()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim x = <a>
<b>
aa
</b>
</a>
Dim x = <a b="1" c=<%= 2 %>>hello<!-- comment --><?pi target ?></a>
End Module
]]>)
'Dim x = <a b="1" c=<%= 2 %>></a>
End Sub
<Fact>
Public Sub ParseCDATA()
' Basic xml literal test
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <a><![CDATA[abcde]]></a>" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseEmbeddedExpression()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim y = <a><%= 1 %></a>
End Module
]]>)
End Sub
<Fact(), WorkItem(545537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545537")>
Public Sub ParseNameWhitespace()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim b = <x/>.@<xml:
x>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "x"))
End Sub
<Fact(), WorkItem(529879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529879")>
Public Sub ParseFWPercent()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <x y=<%= 1 ]]>.Value & ChrW(65285) & <![CDATA[>/>
End Module
]]>.Value)
End Sub
<Fact>
Public Sub ParseAccessorSpaceDisallowed()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/>.@ _
x
Dim y = <y/>.@
y
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31146"/>
<error id="30188"/>
</errors>)
End Sub
<Fact(), WorkItem(546401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546401")>
Public Sub ParseAccessorSpaceDisallowed01()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module Program
Dim x = <x/>.<
x>
Dim y = <y/>.<x >
End Module
VB
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "VB"))
End Sub
<WorkItem(531396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531396")>
<Fact()>
Public Sub ParseEmbeddedExpressionAttributeNoSpace()
ParseAndVerify(<![CDATA[
Module M
Private x = <x<%= Nothing %>/>
End Module
]]>)
' Dev11 does not allow this case.
ParseAndVerify(<![CDATA[
Module M
Private x = <x<%="a"%>="b"/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Private x = <x a="b"c="d"/>
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlWhiteSpace, "c"))
ParseAndVerify(<![CDATA[
Module M
Private x = <x a="b"<%= Nothing %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%= Nothing %>a="b"/>
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlWhiteSpace, "a"))
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%= Nothing %><%= Nothing %>/>
End Module
]]>)
' Dev11 does not allow this case.
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%="a"%>="b"<%="c"%>="d"/>
End Module
]]>)
End Sub
<Fact>
Public Sub ParseEmbeddedExpressionAttributeSpace()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M1
Dim x = <x <%= "a" %>=""/>
End Module
]]>)
End Sub
<Fact>
Public Sub BC31169ERR_IllegalXmlStartNameChar_ParseMissingGT()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim y1 = <a / >
dim y2 = <a </a>
dim y3 = <a ? ? ?</a>
End Module
]]>, <errors>
<error id="31177"/>
<error id="30636"/>
<error id="31169"/>
<error id="30035"/>
<error id="31169"/>
<error id="31169"/>
</errors>)
End Sub
<WorkItem(641680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641680")>
<Fact>
Public Sub ParseDocumentationComment()
ParseAndVerify(<![CDATA[
''' <summary?
Class C
End Class
]]>)
ParseAndVerify(<![CDATA[
''' <summary?
Class C
End Class
]]>,
VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
</errors>)
End Sub
<WorkItem(641680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641680")>
<Fact>
Public Sub ParseDocumentationComment2()
ParseAndVerify(<![CDATA[
''' <summary/>
Class C
End Class
]]>)
End Sub
<WorkItem(551848, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551848")>
<Fact()>
Public Sub KeywordAndColonInXmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@Sub:a
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@p:Sub
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub Regress12668_NoEscapingOfAttrAxis()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@[Sub]
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@[Sub]:a
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@p:[Sub]
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
End Sub
<Fact>
Public Sub Regress12664_IllegalXmlNameChars()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <a/>.@豈
Dim y = <a/>.@a豈
End Module
]]>, <errors>
<error id="31169"/>
<error id="31170"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a/>.@xml:y
Dim y = <a/>.@xml:y
End Module
]]>, <errors>
<error id="31169"/>
<error id="31170"/>
</errors>)
End Sub
<Fact>
Public Sub BC31159ERR_ExpectedXmlEndEmbedded_ParseMissingEmbbedErrorRecovery()
' Basic xml literal test
ParseAndVerify(<![CDATA[
module m1
sub s
dim x = <a a1=<%=1 <!-- comment --> </a>
end sub
end module
]]>, <errors>
<error id="31159"/>
</errors>)
End Sub
<Fact>
Public Sub BC30636ERR_ExpectedGreater_ParseMissingGreaterTokenInEndElement()
' Basic xml literal test
ParseAndVerify(<![CDATA[
module m1
dim x = <a b="1" c =<%= 2 + 3 %>></a
end module
]]>, <errors>
<error id="30636"/>
</errors>)
End Sub
<Fact>
Public Sub ParseAttributeMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p.@a:b
dim a1=p.
@a:b
end module
]]>)
End Sub
<Fact>
Public Sub ParseElementMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p.<a:b>
dim a2=p.
<a:b>
end module
]]>)
End Sub
<Fact>
Public Sub ParseDescendantMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p...<a:b>
dim a2=p...
<a:b>
end module
]]>)
End Sub
<WorkItem(875151, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyCDATA()
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <![CDATA[]]>" & vbCrLf &
"End Module")
End Sub
<WorkItem(875156, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyPI()
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <?pi ?>" & vbCrLf &
"Dim y = <?pi?>" & vbCrLf &
"Dim z = <?pi abcde?>" & vbCrLf &
"End Module")
End Sub
<WorkItem(874435, "DevDiv/Personal")>
<Fact>
Public Sub ParseSignificantWhitespace()
ParseAndVerify(<![CDATA[
module m1
dim x =<ns:e>
a <ns:e> <
</ns:e>
</ns:e>
end module
]]>).
VerifyOccurrenceCount(SyntaxKind.XmlTextLiteralToken, 3)
End Sub
<Fact>
Public Sub ParseXmlNamespace()
ParseAndVerify(<![CDATA[
module m1
Dim x = GetXmlNamespace(p)
end module
]]>)
End Sub
<Fact>
Public Sub BC30203ERR_ExpectedIdentifier_ParseDescendantMemberAccessWithEOLError()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
sub s
dim a1=p..
.<a:b>
end sub
end module
]]>,
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""))
End Sub
<WorkItem(539502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539502")>
<Fact>
Public Sub ParseAttributeWithLeftDoubleQuotationMark()
ParseAndVerify(<![CDATA[
Module M
Dim x = <tag attr=“"/>“/>
End Module
]]>)
End Sub
<WorkItem(539502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539502")>
<Fact>
Public Sub ParseAttributeWithRegularDoubleQuotationMark()
ParseAndVerify(<![CDATA[
Module M
Dim x = <tag attr="abc/>"/>
End Module
]]>)
End Sub
<WorkItem(878042, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeValueSpecialCharacters()
ParseAndVerify(<![CDATA[
module module1
sub main()
dim x1 = <goo attr1="& < > ' ""></goo>
end sub
end module
]]>)
End Sub
<WorkItem(879417, "DevDiv/Personal")>
<Fact>
Public Sub ParsePrologue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <?xml version="1.0" encoding="utf-8"?>
<root/>
End Sub
End Module
]]>)
End Sub
<WorkItem(879562, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeAccessExpression()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <a b="goo" />
Dim y = x.@b
End Sub
End Module
]]>)
End Sub
<WorkItem(879678, "DevDiv/Personal")>
<Fact>
Public Sub BC31163ERR_ExpectedSQuote_ParseAttribute()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <goo attr1='qqq"></>
End Sub
End Module
]]>,
<errors>
<error id="31163"/>
</errors>)
End Sub
<WorkItem(880383, "DevDiv/Personal")>
<Fact>
Public Sub ParseMultilineCDATA()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" Dim x = <![CDATA[" & vbCrLf &
" ]]>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseMultilineCDATAVariousEOL()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" Dim x = <![CDATA[" & vbCrLf &
"abcdefghihjklmn" & vbCr &
" " & vbLf &
" ]]>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<WorkItem(880401, "DevDiv/Personal")>
<Fact>
Public Sub ParseMultilineXComment()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <!--
-->
End Sub
End Module
]]>)
End Sub
<WorkItem(880793, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <outer><%= _
<otherXml></otherXml>
%></outer>
End Sub
End Module
]]>)
End Sub
<WorkItem(880798, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlProcessingInstructionAfterDocument()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <?xml version="1.0"?>
<a><?PI target2?></a>
<?PI target?>
End Sub
End Module
]]>)
End Sub
<WorkItem(881535, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlCDATAContainingImports()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" scenario = <scenario><![CDATA[" & vbCrLf &
"Imports Goo" & vbCrLf &
" ]]></scenario>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<WorkItem(881819, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseXmlQuestionMar()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x =<?></?>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
End Sub
<WorkItem(881822, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlUnterminatedXElementStartWithComment()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <
'
Dim y = <
End Sub
End Module
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30636"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30636"/>
<error id="31146"/>
<error id="31177"/>
</errors>)
End Sub
<WorkItem(881823, "DevDiv/Personal")>
<Fact>
Public Sub BC31175ERR_DTDNotSupported()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim a2 = <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, world!</greeting>
End Sub
End Module
]]>,
<errors>
<error id="31175"/>
</errors>)
End Sub
<WorkItem(881824, "DevDiv/Personal")>
<Fact>
Public Sub BC31172ERR_EmbeddedExpression_Prologue()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <?xml version="1.0" encoding=<%= encoding %>?><element/>
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
</errors>
)
End Sub
<WorkItem(881825, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeEmbeddedExpressionImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <subnode att=
<%=
42
%>
/>
End Sub
End Module
]]>)
End Sub
<WorkItem(881828, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlNamespaceImports()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns="http://microsoft.com">
]]>)
End Sub
<WorkItem(881829, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionLambdaImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim k = <xml><%= Function()
Return {1
}
End Function %>
</xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(881820, "DevDiv/Personal")>
<WorkItem(882380, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlElementContentEntity()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <element><</>
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim buildx = <xml><></xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(882421, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeAccessorBracketed()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns = "goo">
Imports <xmlns:n-s- = "goo2">
Module Module1
Sub Main()
Dim ele3 = <ns:e/>
ele3.@<n-s-:A-A> = <e><%= "hello" %></e>.Value.ToString()
End Sub
End Module
]]>)
End Sub
<WorkItem(882460, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeAccessorInWith()
ParseAndVerify(<![CDATA[
Module Module1
Class Customer : Inherits XElement
Sub New()
MyBase.New(<customer/>)
End Sub
End Class
Sub Main()
Dim oldCust = <customer name="Sally"/>
With oldCust
Dim newCust As New Customer With {.Name = .@name}
End With
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub BC31178ERR_ExpectedSColon()
Dim tree = Parse(<![CDATA[
Imports <xmlns:p="0">
Module M
Private F = <x><Z</x>
End Module
]]>)
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC31178: Expected closing ';' for XML entity.
Imports <xmlns:p="0">
~~~~~
BC31178: Expected closing ';' for XML entity.
Private F = <x><Z</x>
~~~~~
]]></errors>)
End Sub
<WorkItem(882874, "DevDiv/Personal")>
<Fact>
Public Sub BC31178ERR_ExpectedSColon_ParseXmlEntity()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1="&"></goo>
End Sub
End Module
]]>,
<errors>
<error id="31178"/>
</errors>)
End Sub
<Fact>
Public Sub BC31166ERR_StartAttributeValue_ParseXmlAttributeUnquoted()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1=before&after></goo>
End Sub
End Module
]]>,
<errors>
<error id="31166"/>
</errors>)
End Sub
<Fact>
Public Sub BC31155ERR_QuotedEmbeddedExpression_ParseXmlAttribute()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1="<%= %>"></goo>
End Sub
End Module
]]>,
<errors>
<error id="31155"/>
</errors>)
End Sub
<WorkItem(882898, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionXmlAccessorLineContinuation()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns="lower">
Module Module1
Sub Main()
Dim A1 = <ns:book>
<title name="Debug Applications">
<award>
<ns:award ns:year="1998" name="MS award"/>
<ns:award ns:year="1998" name="Peer Recognition"/>
</award>
</title>
</ns:book>
Dim frag = <fragment>
<%= From i In A1.<ns:book> _
.<title> _
Select i.@name 'qqq
%>
</fragment>
End Sub
End Module
]]>)
End Sub
<WorkItem(883277, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeEmbeddedExpressionLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <e a=
<%= 3 %>></e>
End Sub
End Module
]]>)
End Sub
<WorkItem(883619, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = New Object() {<?xml version="1.0"?>
<%= <e/> %>, _
<?xml version="1.0"?>
<%= <e/> %> _
}
End Sub
End Module
]]>)
End Sub
<WorkItem(883620, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEntityNumericCharacterReference()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim el3 = <element>Ӓ < F</element>
End Sub
End Module
]]>)
End Sub
<WorkItem(883626, "DevDiv/Personal")>
<Fact>
Public Sub BC31153ERR_MissingVersionInXmlDecl_ParseXmlEmbeddedExpressionInPrologue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <?xml <%= New XAttribute("some", "1.0") %> version="1.0" ?><e/>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31172"/>
<error id="30249"/>
<error id="31153"/>
</errors>)
End Sub
<WorkItem(883628, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlNameRem()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim A1 As XElement = <Rem />
Dim x = A1.<Rem>
End Sub
End Module
]]>)
End Sub
<WorkItem(883651, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionContainsQuery()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i3 = <xml>
<%=
From el
In {1, 2, 3}
Select (<node><%= el %></node>)
%>
</xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(883734, "DevDiv/Personal")>
<Fact>
Public Sub BC31160ERR_ExpectedXmlEndPI_ParseXmlPrologueInQuery()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x31 = From i In {}
Select <?xml version="1.0">
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(887785, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlImplicitExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim xml =
_
<xml></xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(887792, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlElementCharDataSibling()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim b = <fragment>
<element></element>
Sometext
</fragment>
End Sub
End Module
]]>)
End Sub
<WorkItem(887798, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlGetXmlNamespaceRem()
ParseAndVerify(<![CDATA[
Imports <xmlns:Rem = "http://testcase">
Module Module1
Sub Main()
Dim y = GetXmlNamespace(Rem) + "localname"
End Sub
End Module
]]>)
End Sub
<WorkItem(888542, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlDocumentStopsParsingXml()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Dim x_XML = <?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact>
<name><Prefix>Mr</Prefix>Adam Braden</name>
<phone>215 123456</phone>
</contact>
</contacts>
End Sub
End Module
]]>)
End Sub
<WorkItem(894127, "DevDiv/Personal")>
<Fact()>
Public Sub BC30001ERR_ParseXmlDocumentWithExpressionBody_NoParseError()
ParseAndVerify(<![CDATA[
Dim b = <?xml version="1.0"?>
<%= <e><%= j.e & i.e %></e> %>
]]>)
End Sub
<WorkItem(893969, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlPrecededByExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Namespace DynLateSetLHS010
Friend Module DynLateSetLHS010mod
Sub DynLateSetLHS010()
Dim el = _
<name1>
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30026"/>
<error id="30625"/>
<error id="30626"/>
</errors>)
End Sub
<WorkItem(893973, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlPrecededByExplicitLineContinuationLine()
ParseAndVerify(<![CDATA[
Namespace DynLateSetLHS010
Friend Module DynLateSetLHS010mod
Sub DynLateSetLHS010()
Dim el =
_
<name1>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndNamespace, "Namespace DynLateSetLHS010"),
Diagnostic(ERRID.ERR_ExpectedEndModule, "Friend Module DynLateSetLHS010mod"),
Diagnostic(ERRID.ERR_EndSubExpected, "Sub DynLateSetLHS010()"),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_"),
Diagnostic(ERRID.ERR_StandaloneAttribute, ""),
Diagnostic(ERRID.ERR_LocalsCannotHaveAttributes, "<name1>"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""))
End Sub
<WorkItem(897813, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlExplicitLineContinuationLineFollowedByLessThan()
ParseAndVerify(<![CDATA[
' This isn't really xml
Dim el =
_
< ]]>,
<errors>
<error id="30201"/>
<error id="30999"/>
<error id="30203"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(898451, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseXmlErrorBeginningWithLessThanGreaterThan()
ParseAndVerify(<![CDATA[
Module TestModule
Sub Main()
Dim A = <>
<ns:book collection="library">
<%= <>
<ns:award ns:year="1998" name="Booker Award"/>
</> %>
</ns:book>
<%= returnXml(<args></args>, str) %>
</>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31146"/>
</errors>)
End Sub
<WorkItem(885888, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlErrorNameStartingWithExclamation()
ParseAndVerify(<root>
Class Class1
Sub Main()
Dim y2 = <! [CDATA[]]>
'</> 'Required for error recovery
End Sub
End Class
</root>.Value,
<errors>
<error id="31146"/>
<error id="31169"/>
<error id="30636"/>
<error id="31169"/>
<error id="31170"/>
</errors>)
End Sub
<WorkItem(889091, "DevDiv/Personal")>
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingPercentGreaterThanToken()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <abc def=<%=baz >
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingExpression()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <%=
End Sub
End Class
]]>,
Diagnostic(ERRID.ERR_EmbeddedExpression, "<%="),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""))
End Sub
<WorkItem(889091, "DevDiv/Personal")>
<Fact()>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingPercentGreaterThanTokenWithColon()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <abc bar=<%=baz >:
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="31159"/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(899741, "DevDiv/Personal")>
<Fact>
Public Sub ParseIncompleteProcessingInstruction()
ParseAndVerify(<![CDATA[
Dim y As Object() = New Object() {<goo/>, <?pi
]]>,
<errors>
<error id="30370"/>
<error id="31160"/>
</errors>)
End Sub
<WorkItem(899919, "DevDiv/Personal")>
<Fact>
Public Sub ParseIncompleteXmlDoc()
ParseAndVerify(<![CDATA[
Dim rss = <?xml vers]]>,
<errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(900238, "DevDiv/Personal")>
<Fact>
Public Sub ParseGetXmlNamespace()
ParseAndVerify(<![CDATA[
Dim ns = GetXmlNamespace(
]]>,
<errors>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(900250, "DevDiv/Personal")>
<Fact>
Public Sub ParseExprHoleInXMLDoc()
ParseAndVerify(<![CDATA[
Sub New()
MyBase.New(<?xml version="1.0" encoding=<%=
]]>,
<errors>
<error id="30026"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(903139, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrXmlDoc()
ParseAndVerify(<![CDATA[Dim x1 = <?xml q ?>]]>,
<errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(903556, "DevDiv/Personal")>
<Fact>
Public Sub BC31198ERR_XmlEndCDataNotAllowedInContent_ParseCDataCloseTagInContent()
'Could not use CDATA since code involves CDATA close tag
Dim code = "Module M1" & vbCrLf &
"Dim x = <doc>]]></doc>" & vbCrLf &
"End Module"
ParseAndVerify(code,
<errors>
<error id="31198"/>
</errors>)
End Sub
<WorkItem(903557, "DevDiv/Personal")>
<Fact>
Public Sub ParseBadXmlDocument()
ParseAndVerify(<![CDATA[
Module M1
Dim x = <?xml name value ?>
<test/>
End Module
]]>, <errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
</errors>)
End Sub
<WorkItem(903564, "DevDiv/Personal")>
<Fact>
Public Sub BC31171ERR_IllegalXmlCommentChar()
ParseAndVerify(<![CDATA[
Module M1
Dim x = <!-- a -- a -->
End Module
]]>, <errors>
<error id="31171"/>
</errors>)
End Sub
<WorkItem(903592, "DevDiv/Personal")>
<Fact>
Public Sub BC31173ERR_ExpectedXmlWhiteSpace_ParseAttributeSpace()
ParseAndVerify(<![CDATA[
Module M1
Dim d =
<a b="c"d="e"/>
End Module
]]>, <errors>
<error id="31173"/>
</errors>)
End Sub
<WorkItem(903586, "DevDiv/Personal")>
<Fact>
Public Sub BC31174ERR_IllegalProcessingInstructionName()
ParseAndVerify(<![CDATA[
Module M1
Dim f = <?xmL?>
End Module
]]>, <errors>
<error id="31174"/>
</errors>)
End Sub
<WorkItem(903938, "DevDiv/Personal")>
<Fact>
Public Sub ParseDeclaration_ERR_ExpectedEQ()
ParseAndVerify(<![CDATA[
Module M1
Dim f =
<?xml version eq '1.0' ?>
<doc/>
End Module
]]>, <errors>
<error id="30249"/>
</errors>)
End Sub
<WorkItem(903951, "DevDiv/Personal")>
<Fact>
Public Sub BC31177ERR_IllegalXmlWhiteSpace_ParseXmlNameStartsWithNewLine()
ParseAndVerify(<![CDATA[
Module M1
Dim x1 = < doc/>
Dim x2 = <
doc/>
dim x3 = < a :b />
dim x4 = <a: b = "1" />
dim x5=<a:b></ a : b >
dim x6=<a b : c="1" />
end module
]]>, Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "b"),
Diagnostic(ERRID.ERR_ExpectedXmlName, ""),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "b"),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "c"))
End Sub
<Fact>
Public Sub BC31177ERR_IllegalXmlWhiteSpace_ParseBracketedXmlQualifiedName()
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@< a>
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@< p:a>
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@<a >
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@<p:a >
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
End Sub
<WorkItem(903972, "DevDiv/Personal")>
<Fact>
Public Sub BC31150ERR_MismatchedXmlEndTag()
ParseAndVerify(<![CDATA[
Module M1
Dim d =
<doc></DOC>
End Module
]]>, <errors>
<error id="31150"/>
<error id="31151"/>
</errors>)
End Sub
<WorkItem(903986, "DevDiv/Personal")>
<Fact>
Public Sub BC31181ERR_InvalidAttributeValue1_BadVersion()
ParseAndVerify(<![CDATA[
Module M1
Dim f =
<?xml version="1.0?"?><e></e>
End Module
]]>, <errors>
<error id="31181"/>
</errors>)
End Sub
<WorkItem(889870, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlRequiresParensNotReported()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim f = From e As XProcessingInstruction In <?xpi Val=2?>
End Sub
End Class
]]>)
End Sub
<WorkItem(889866, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEntityReferenceErrorNotExpected()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim x3 = <goo attr1="x < A"></goo>
End Sub
End Class
]]>)
End Sub
<WorkItem(889865, "DevDiv/Personal")>
<Fact>
Public Sub BC30026ERR_EndSubExpected_ParseMoreErrorExpectedGreater()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
dim x1 = <goo attr1='qqq"></>
Sub
End Class
]]>,
<errors>
<error id="30026"/>
<error id="31163"/>
<error id="30289"/>
<error id="30026"/>
<error id="30203"/>
</errors>)
End Sub
<WorkItem(889898, "DevDiv/Personal")>
<Fact>
Public Sub ParseMoreErrorsExpectedLTAndExpectedXmlEndPI()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
#If True Then
Dim x31 = From i In (<ns:e <%= <ns:e><%= ns & "hello" %></ns:e> %>></ns:e>.<ns:e>) _
Where i.Value <> (<<%= <ns:e><%= ns %></ns:e>.Name %>><%= ns %></>.Value) _
Select <?xml version="1.0">
'</> 'Required for error recovery
#Else
'COMPILERWARNING : 42019, "ns & \"hello\""
#End If
End Sub
End Class
]]>,
<errors>
<error id="31146"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(885799, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar_ParseErrorMismatchSyntaxVSExpectedGreater()
ParseAndVerify(<![CDATA[
Class Class1
Sub Scenario1()
Dim b = new integer? << <goo/> << <what?/>
End Sub
End Class
]]>,
<errors>
<error id="31170"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(885790, "DevDiv/Personal")>
<Fact>
Public Sub BC31150ERR_MismatchedXmlEndTag_ParseErrorMismatchExpectedGreaterVSSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Sub Main()
Dim x = <e a='<%="v"%>'></a>
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="31155"/>
<error id="31150"/>
</errors>)
End Sub
<WorkItem(924043, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionInXmlName()
ParseAndVerify(<![CDATA[
Module TestModule
Sub Main()
Dim B = <root>
<<%= <abc><root>name</root></abc>...<root>.value %>></>
</root>
End Sub
End Module
]]>)
End Sub
<WorkItem(925953, "DevDiv/Personal")>
<WorkItem(927711, "DevDiv/Personal")>
<Fact>
Public Sub BC31165ERR_ExpectedLT_ParseXmlErrorRecoveryMissingEnd()
ParseAndVerify(<![CDATA[
Module TestModule
dim x=<a><b></a>
End Module
]]>, <errors>
<error id="31151"/>
<error id="31165"/>
<error id="31146"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(926593, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithNamespace()
ParseAndVerify(<![CDATA[
Namespace ExpandoContext02
Friend Module ExpandoContext02mod
Sub ExpandoContext02()
Dim x10 = <?xml version="1.0"?><%= <e <%= New XAttribute("a", "v") %> <%= <e ns:a=<%= "v" %> <%= "b" %>="v"/> %>></e> %>
Dim a = <e <%= XName.Get("a", GetXmlNamespace(ns).ToString) %>="v"><ns:EE-E>SUCCESS</ns:EE-E></e>
End Sub
End Module
End Namespace
]]>)
End Sub
<WorkItem(926595, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithStatement()
ParseAndVerify(<![CDATA[
Module Test
Sub Method()
Dim b3 = <<%= "e" %> <%= New With {New With {New With {New With {(<e><%= 1 %></e>.Value << 3 >> 1).ToString.ToCharArray}.ToCharArray}.ToCharArray}.ToCharArray}.ToCharArray %>/>
End Sub
End Module
]]>)
End Sub
<WorkItem(926595, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrorXmlEmbeddedExpressionInvalidValue()
ParseAndVerify(<![CDATA[
Module Test
Sub Method()
Dim x7 = <a><%= Class %></a>
Dim x71 = <a><<%= Function %>/></a>
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30035"/>
<error id="30199"/>
<error id="30198"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(527094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527094")>
<WorkItem(586871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586871")>
<Fact>
Public Sub BC31197ERR_FullWidthAsXmlDelimiter_ParseXmlStart()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <xml></xml>
Dim y =<STAThread/>
Dim z =<!-- Not a comment --!>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"))
'Note that the first "<" character above
'is a full-width unicode character (not ascii).
End Sub
<WorkItem(927138, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlLargeNumberOfTrailingNewLines()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Try
Dim d =
<?xml version="1.0"?>
<root/>
Catch ex as Exception
End Try
End Sub
End Module
]]>)
End Sub
<WorkItem(927387, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeValueThatStartsOnNewLine()
ParseAndVerify(<![CDATA[
Module M1
Dim doc =
<?xml
version
=
'1.0'
?>
<doc/>
End Module
]]>)
End Sub
<WorkItem(927823, "DevDiv/Personal")>
<Fact>
Public Sub BC31154ERR_IllegalAttributeInXmlDecl_ParseBadXmlWithFullWidthContent()
ParseAndVerify(<![CDATA[
Module Module2
Sub Main()
Dim code = <?xml version="1.0"?>
<xml ver="1.0" ver0=`1.0' ver1=`1.0` ver2='1.0'>
<<%="xml"%> <%="xml"%>=<%="xml"%>/>
<%= <!--version="1.0"--><?ver?> <![CDATA[version="1.0"]]> %>
</>
End Sub
End Module]]>,
<errors>
<error id="31154"/>
<error id="31169"/>
<error id="30249"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31153"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
'Note that the characters after "<?xml " upto and including "</>" above
'are full-width unicode characters (not ascii).
End Sub
<WorkItem(927834, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar_ParseXmlWithFullWidthContentInEmbeddedExpression()
'TODO: This is a change in behavior from Dev10.
'Please move this test to BreakingChanges.vb if this is a change that we want to keep.
ParseAndVerify(<![CDATA[
Module Module2
Sub Main()
Dim code = <xml ver="hi"><<%="xml"%>/></>
End Sub
End Module]]>, <errors>
<error id="31169"/>
</errors>)
'Note that the characters starting from <%= to %> (both inclusive) above
'are full-width unicode characters (not ascii).
End Sub
<WorkItem(928408, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmbeddedXMLWithCRLFInTag()
ParseAndVerify(<![CDATA[Dim x12 = <e><%= <e
]]>, <errors>
<error id="31151"/>
<error id="31151"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(930274, "DevDiv/Personal")>
<Fact>
Public Sub ParseLegalValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim doc =
<?xml version='1.0' standalone='yes'?><e/>
Dim doc2 =
<?xml version='1.0' standalone='no'?><e/>
End Module]]>)
End Sub
<WorkItem(930256, "DevDiv/Personal")>
<Fact>
Public Sub BC31182ERR_InvalidAttributeValue2_ParseEmptyValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim x = <?xml version="1.0" standalone=''?><doc/>
End Module
]]>,
<errors>
<error id="31182"/>
</errors>)
End Sub
<WorkItem(930757, "DevDiv/Personal")>
<Fact>
Public Sub BC31182ERR_InvalidAttributeValue2_ParseBadValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim doc =
<?xml version='1.0' standalone='YES'?><e/>
Dim doc2 =
<?xml version='1.0' standalone='nO'?><e/>
End Module]]>, <errors>
<error id="31182"/>
<error id="31182"/>
</errors>)
End Sub
<WorkItem(537183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537183")>
<WorkItem(930327, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseBadEncodingAttributeInPrologue()
ParseAndVerify(<![CDATA[module m1
dim x = <?xml version="1.0" "UTF-8"encoding=?>
<!--* wrong ordering in above EncodingDecl *--><root/>
end module
module m2
dim x = <?xml version="1.0"encoding="UTF-8"?>
<!--* missing white space in above EncodingDecl *-->
<root/>
end module]]>, <errors>
<error id="31146" message="XML name expected." start="38" end="39"/>
<error id="31173" message="Missing required white space." start="161" end="169"/>
</errors>)
End Sub
<WorkItem(930330, "DevDiv/Personal")>
<Fact>
Public Sub BC30037ERR_IllegalChar_ParseIllegalXmlCharacters()
ParseAndVerify("Module M1" & vbCrLf &
"Dim doc = " & vbCrLf &
"<?xml version=""1.0""?><doc></doc>" & vbCrLf &
"End Module" & vbCrLf &
vbCrLf &
"Module M2" & vbCrLf &
"Dim frag = " & vbCrLf &
"<e><doc></doc></>" & vbCrLf &
"End Module", <errors>
<error id="30037"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(538550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538550")>
<WorkItem(538551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538551")>
<Fact>
Public Sub ParseXmlStringIncludingSmartQuotes()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr=""" & ChrW(8216) & """ />" & vbCrLf &
"Dim x2 = <tag attr=""" & ChrW(8217) & """ />" & vbCrLf &
"Dim x3 = <tag attr=""" & ChrW(8220) & """ />" & vbCrLf &
"Dim x4 = <tag attr=""" & ChrW(8221) & """ />" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseXmlSmartSingleString()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr= " & ChrW(8216) & "text" & ChrW(8216) & "/>" & vbCrLf &
"Dim x2 = <tag attr= " & ChrW(8216) & "text" & ChrW(8217) & "/>" & vbCrLf &
"Dim x3 = <tag attr= " & ChrW(8217) & "text" & ChrW(8216) & "/>" & vbCrLf &
"Dim x4 = <tag attr= " & ChrW(8217) & "text" & ChrW(8217) & "/>" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseXmlSmartDoubleString()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr= " & ChrW(8220) & "text" & ChrW(8220) & "/>" & vbCrLf &
"Dim x2 = <tag attr= " & ChrW(8220) & "text" & ChrW(8221) & "/>" & vbCrLf &
"Dim x3 = <tag attr= " & ChrW(8221) & "text" & ChrW(8220) & "/>" & vbCrLf &
"Dim x4 = <tag attr= " & ChrW(8221) & "text" & ChrW(8221) & "/>" & vbCrLf &
"End Module")
End Sub
<WorkItem(544979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544979")>
<Fact()>
Public Sub ParseEmbeddedLambda()
ParseAndVerify(<![CDATA[
Module Program
Dim x = <x <%= Sub() Return %>/>
End Module
]]>.Value)
End Sub
<WorkItem(538241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538241")>
<Fact>
Public Sub ParseXmlMemberFollowedByWSColon()
Dim tree = ParseAndVerify(<![CDATA[
Module A
Sub Main()
Dim x = <x/>.@x : Console.WriteLine()
End Sub
End Module
]]>.Value)
Dim main = tree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1)
Dim stmt1 = main.ChildNodesAndTokens()(1)
Dim stmt2 = main.ChildNodesAndTokens()(2)
Dim colon = stmt1.ChildNodesAndTokens().LastOrDefault().GetTrailingTrivia().Last
Assert.Equal(colon.Kind, SyntaxKind.ColonTrivia)
Assert.Equal(stmt2.Kind(), SyntaxKind.ExpressionStatement)
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(stmt2.AsNode, ExpressionStatementSyntax).Expression.Kind)
Dim exprStmt = TryCast(stmt2.AsNode, ExpressionStatementSyntax)
Dim invocExp = TryCast(exprStmt.Expression, InvocationExpressionSyntax)
Dim memAccess = TryCast(invocExp.Expression, MemberAccessExpressionSyntax)
Assert.Equal(memAccess.Expression.ToString, "Console")
Assert.Equal(memAccess.Name.ToString, "WriteLine")
End Sub
<WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")>
<Fact()>
Public Sub Bug7954()
' 0123456789ABC
Dim code = <![CDATA[Dim=<><%=">
<]]>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(code)
Assert.Equal(code, tree.GetRoot().ToString())
End Sub
<WorkItem(545076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545076")>
<Fact()>
Public Sub WhitespaceInClosingTag()
ParseAndVerify(<![CDATA[
Module M1
Sub Main
Dim x = <goo>< /goo>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, "< /"),
Diagnostic(ERRID.ERR_ExpectedLT, ""))
End Sub
<WorkItem(529395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529395")>
<Fact()>
Public Sub Bug12644()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() If True Then Else %></x>
End Module
]]>)
End Sub
<WorkItem(544399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544399")>
<Fact()>
Public Sub BrokenEndElementStartInXmlDoc()
ParseAndVerify(<![CDATA[
''' </
Module M
End Module
]]>,
VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
Diagnostic(ERRID.WRN_XMLDocParseError1, "</").WithArguments("XML end element must be preceded by a matching start element."),
Diagnostic(ERRID.WRN_XMLDocParseError1, "").WithArguments("'>' expected."))
End Sub
<WorkItem(547320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547320")>
<WorkItem(548952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548952")>
<Fact()>
Public Sub Bug18598()
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= F(End
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="30198"/>
<error id="31159"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(+
Return
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(548996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548996")>
<Fact()>
Public Sub Bug548996()
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= x +
Return
%>/>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_MissingXmlEndTag, <![CDATA[<<%= x +
Return
%>]]>),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_Syntax, "Return"),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""),
Diagnostic(ERRID.ERR_IllegalXmlStartNameChar, "%").WithArguments("%", "&H25"),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ""))
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= x +
Return : %>/>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_MissingXmlEndTag, <![CDATA[<<%= x +
Return : %>]]>),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_Syntax, "Return"),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ":"),
Diagnostic(ERRID.ERR_IllegalXmlStartNameChar, "%").WithArguments("%", "&H25"),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ""))
End Sub
<WorkItem(575763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575763")>
<Fact()>
Public Sub Bug575763()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
%>/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31169"/>
<error id="30249"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/> %>
c=""/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
c=""/>
End Module
]]>,
<errors>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
End Sub
<WorkItem(575780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575780")>
<Fact()>
Public Sub Bug575780()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Function() :
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() :
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() : Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Return :
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else :
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else If False Then Return Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else If False Then Return Else : Return
End Module
]]>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then Else If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then If True Then Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then Else If True Then Else :
End Module
]]>)
End Sub
''' <summary>
''' As above but with lambda inside embedded expression.
''' </summary>
<WorkItem(575780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575780")>
<Fact()>
Public Sub Bug575780_EmbeddedExpression()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <<%= Sub() : Return %>/>
End Sub
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026" message="'End Sub' expected."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <<%= Sub() Return : %>/>
End Sub
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026" message="'End Sub' expected."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Return : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Return : Return %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else : %>/>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else Return : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else Return : Return %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If False Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else If False Then Return Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else If False Then Return Else : Return %>/>
End Module
]]>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then Else If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then Else If True Then Else : %>/>
End Module
]]>)
End Sub
<WorkItem(577617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577617")>
<Fact()>
Public Sub Bug577617()
ParseAndVerify(String.Format(<source>
Module M
Dim x = {0}x/>
End Module
</source>.Value, FULLWIDTH_LESS_THAN_SIGN),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"))
End Sub
<WorkItem(611206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611206")>
<Fact()>
Public Sub Bug611206()
ParseAndVerify(<![CDATA[
Module M
Dim x = <!DOCTYPE
End Module
]]>,
<errors>
<error id="31175" message="XML DTDs are not supported."/>
</errors>)
End Sub
<WorkItem(602208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602208")>
<Fact()>
Public Sub Bug602208()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<!-- -->
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
) %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root/>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root>
</root>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root></>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<%= <root/> %>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
End Sub
<WorkItem(598156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598156")>
<Fact()>
Public Sub Bug598156()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<!-- -->
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<?p?>.ToString() %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<!-- -->
)
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
) %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
, Nothing)
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
, Nothing) %>/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30198" message="')' expected."/>
<error id="31159"/>
<error id="30636"/>
<error id="31169"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?><x/>
Dim y = <?xml version="1.0"?><y/>
End Module
]]>)
End Sub
<WorkItem(598799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598799")>
<Fact()>
Public Sub Bug598799()
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <x/>
Distinct
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
' Comment
Distinct
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/> ' Comment
Distinct
End Module
]]>)
End Sub
<WorkItem(601050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601050")>
<Fact()>
Public Sub Bug601050()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If False Then Else
Dim y = <x/> %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<WorkItem(601899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601899")>
<Fact()>
Public Sub Bug601899()
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <%= Nothing %>
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <?xml version="1.0"?><%= Nothing %>
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <!--
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Function F(
Return <![CDATA[
End Function
End Module
</source>.Value,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <? :
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
End Sub
<Fact()>
Public Sub DocumentWithTrailingMisc()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root/>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root>
</root>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root></>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<%= <root/> %>
Select x
End Sub
End Module
]]>)
End Sub
<WorkItem(607253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607253")>
<Fact()>
Public Sub GetXmlNamespaceErrors()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace :
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( :
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y:
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y :
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
' Dev11 reports BC30199: "'(' expected."
' although that seems unnecessary.
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace (y)
End Module
]]>)
End Sub
<WorkItem(607352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607352")>
<Fact()>
Public Sub GetXmlNamespaceErrors_2()
ParseAndVerify(<![CDATA[
Imports <xmlns:y="">
Module M
Dim x = GetXmlNamespace
(y)
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
End Sub
<WorkItem(607560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607560")>
<Fact()>
Public Sub GetXmlNamespaceErrors_3()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( y)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y )
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( )
End Module
]]>)
End Sub
<WorkItem(610345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610345")>
<Fact()>
Public Sub Bug610345()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <%= CBool(
Return
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30201" message="Expression expected."/>
<error id="30198"/>
<error id="30035"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%=
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
M(<<%=
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026"/>
<error id="31151"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F( _
#Const c = 0
) %></>
End Module
]]>,
<errors>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x </x>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $ _
REM Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (<%= F() )
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="31159"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (<%= F() _
)
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="31159"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x
x = <%= F() :::
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
<error id="31159"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $:
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $ 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x %>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x %> :
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x) $ REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x) $ _
REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= {1, 2 3
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30370"/>
<error id="30370"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= New Object()(1
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32014"/>
<error id="30198"/>
<error id="30987"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function(Of T
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36674"/>
<error id="32065"/>
<error id="30199"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function(Of T)
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36674"/>
<error id="32065"/>
<error id="30199"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= If(Nothing) 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="33104"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= If(1, 2 3 REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= F(y z
) %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="32017"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(y z
)
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() a!b c %>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30800"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() a!b c %> :
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="30800"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(671111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/671111")>
<Fact()>
Public Sub Bug671111()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
<y>
<z></z / </y>
</x>
End Module
]]>,
<errors>
<error id="30636"/>
<error id="30636"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x>
<y>
<z></z / </y>
</x>
End Module
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(673558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673558")>
<Fact()>
Public Sub Bug673558()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><
<]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31151"/>
<error id="31146"/>
<error id="30636"/>
<error id="31151"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><
REM]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31151"/>
<error id="31177"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(673638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673638")>
<Fact()>
Public Sub NotLessThan_Imports()
ParseAndVerify(<![CDATA[
Imports <%=xmlns="">
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <%=>
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <%=%>
]]>,
<errors>
<error id="31165"/>
<error id="31169"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports </xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports </>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <?xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <?>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!--xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!-->
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!---->
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <![CDATA[xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <![CDATA[>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify("Imports <![CDATA[]]>",
<errors>
<error id="30203"/>
<error id="30037"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!DOCTYPExmlns="">
]]>,
<errors>
<error id="31165"/>
<error id="31175"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!DOCTYPE>
]]>,
<errors>
<error id="31165"/>
<error id="31175"/>
</errors>)
End Sub
<Fact()>
Public Sub NotLessThan_BracketedXmlName()
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<%= y %>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<%= y %>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.</y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@</y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<?y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<?y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<!--y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<!--y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<![CDATA[y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<![CDATA[y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<!DOCTYPE>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<!DOCTYPE>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(674567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674567")>
<Fact()>
Public Sub Bug674567()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= <p:
y a=""/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31177"/>
<error id="31146"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= <p:
End Module
]]>,
<errors>
<error id="31172"/>
<error id="31151"/>
<error id="31177"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31159"/>
</errors>)
End Sub
<Fact()>
Public Sub XmlNameTokenPossibleKeywordKind()
Const sourceTemplate = "
Module M
Dim x = <{0}:
y a=""/>
End Module
"
Const squiggleTemplate = "<{0}:
y a=""/>
End Module
"
Dim commonExpectedErrors =
{
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, "
"),
Diagnostic(ERRID.ERR_ExpectedXmlName, "y"),
Diagnostic(ERRID.ERR_ExpectedQuote, ""),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "")
}
Dim tree1 = Parse(String.Format(sourceTemplate, "e"))
tree1.GetDiagnostics().Verify(commonExpectedErrors.Concat({Diagnostic(ERRID.ERR_MissingXmlEndTag, String.Format(squiggleTemplate, "e"))}).ToArray())
Dim tree2 = Parse(String.Format(sourceTemplate, "ee"))
tree2.GetDiagnostics().Verify(commonExpectedErrors.Concat({Diagnostic(ERRID.ERR_MissingXmlEndTag, String.Format(squiggleTemplate, "ee"))}).ToArray())
Dim getPossibleKeywordKind = Function(x As XmlNameSyntax) DirectCast(x.Green, InternalSyntax.XmlNameSyntax).LocalName.PossibleKeywordKind
Dim kinds1 = tree1.GetRoot().DescendantNodes().OfType(Of XmlNameSyntax).Select(getPossibleKeywordKind)
Assert.NotEmpty(kinds1)
AssertEx.All(kinds1, Function(k) k = SyntaxKind.XmlNameToken)
Dim kinds2 = tree2.GetRoot().DescendantNodes().OfType(Of XmlNameSyntax).Select(getPossibleKeywordKind)
Assert.Equal(kinds1, kinds2)
End Sub
<Fact()>
Public Sub TransitionFromXmlToVB()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( ' comment
End Module
]]>,
<errors>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(p
End Module
]]>,
<errors>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <xmlns:p=""
Module M
End Module
]]>,
<errors>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<p ' comment
End Module
]]>,
<errors>
<error id="31177"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding=<%=
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding=<%=""%>
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0" encoding=<%=F(
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(682381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682381")>
<Fact()>
Public Sub Bug682381()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= If(1
, 2) %>
End Module
]]>,
<errors>
<error id="31172"/>
<error id="33104"/>
<error id="30198"/>
<error id="31159"/>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(682391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682391")>
<Fact()>
Public Sub Bug682391()
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version <%= e %>
End Module
]]>,
<errors>
<error id="31181"/>
<error id="31172"/>
<error id="30249"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version=1.0 <%= e %>
End Module
]]>,
<errors>
<error id="31181"/>
<error id="31154"/>
<error id="31169"/>
<error id="31173"/>
<error id="31172"/>
<error id="30249"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(682394, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682394")>
<Fact()>
Public Sub Bug682394()
ParseAndVerify(<![CDATA[
Imports <%=:p>
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <<%=:p>>
]]>,
<errors>
<error id="31187"/>
<error id="30636"/>
</errors>)
End Sub
<Fact()>
Public Sub IncompleteMultilineLambdaInEmbeddedExpression()
ParseAndVerify(<![CDATA[
Class C
Dim x = <x><%= Sub()
]]>,
<errors>
<error id="30481"/>
<error id="31151"/>
<error id="36673"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<Fact()>
Public Sub FullWidthEmbeddedExpressionTokens()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<", ToFullWidth("<")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<%", ToFullWidth("<%")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<%=", ToFullWidth("<%=")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("%>", ToFullWidth("%") & ">"),
<errors>
<error id="31172"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("%>", ToFullWidth("%>")),
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(684872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684872")>
<Fact()>
Public Sub Bug684872()
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
_
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
_
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
_
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
</x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<%=x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(693901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/693901")>
<Fact()>
Public Sub Bug693901()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, LINE_SEPARATOR),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, PARAGRAPH_SEPARATOR),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$/>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$=""/>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="31169"/>
</errors>)
End Sub
<WorkItem(716121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716121")>
<Fact()>
Public Sub Bug716121()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, NO_BREAK_SPACE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, IDEOGRAPHIC_SPACE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
' Test all Unicode space characters other than &H20.
For i = &H21 To &HFFFF
Dim c = ChrW(i)
' Note: SyntaxFacts.IsWhitespace(c) considers &H200B as
' space even though the UnicodeCategory is Format.
If (Char.GetUnicodeCategory(c) = Globalization.UnicodeCategory.SpaceSeparator) OrElse
SyntaxFacts.IsWhitespace(c) Then
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, c),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
End If
Next
End Sub
<WorkItem(697114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697114")>
<Fact()>
Public Sub Bug697114()
' No attributes.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
' One attribute.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
' Two attributes, starting with version.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
</errors>)
' Two attributes, starting with unknown.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
' Two attributes, starting with encoding.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
' Two attributes, starting with standalone.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
' Three attributes, starting with version.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
</errors>)
' Three attributes, starting with unknown.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31157"/>
<error id="31153"/>
</errors>)
' Three attributes, starting with encoding.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
' Three attributes, starting with standalone.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
<error id="31157"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31157"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
<error id="31157"/>
<error id="31154"/>
</errors>)
' Four attributes.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
End Sub
''' <summary>
''' Tests that the REM keyword cannot be neither left nor right part of a qualified XML name.
''' But FULLWIDTH COLON (U+FF1A) should never be parsed as a qualified XML name separator, so REM can follow it.
''' Also, the second colon should never be parsed as a qualified XML name separator.
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub NoRemInXmlNames()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@rem
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "@").WithLocation(4, 22))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@rem:goo
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "@").WithLocation(4, 22))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:rem
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "").WithLocation(4, 27))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:rem$
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "").WithLocation(4, 27))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml :rem
End Sub
End Module]]>)
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:goo:rem
End Sub
End Module]]>)
' FULLWIDTH COLON is represented by "~" below
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@goo~rem
End Sub
End Module]]>.Value.Replace("~"c, FULLWIDTH_COLON))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@goo~rem$
End Sub
End Module]]>.Value.Replace("~"c, FULLWIDTH_COLON))
End Sub
<WorkItem(969980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969980")>
<WorkItem(123533, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=123533")>
<Fact>
Public Sub UnaliasedXmlImport_Local()
Dim source = "
Imports <xmlns = ""http://xml"">
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll)
Const bug123533IsFixed = False
If bug123533IsFixed Then
compilation.AssertTheseDiagnostics(<expected><![CDATA[
BC50001: Unused import statement.
Imports <xmlns = "http://xml">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>, False)
Else
compilation.AssertTheseDiagnostics(<expected><![CDATA[
BC50001: Unused import statement.
Imports <xmlns = "http://xml">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31187: Namespace declaration must start with 'xmlns'.
Imports <xmlns = "http://xml">
~
BC30636: '>' expected.
Imports <xmlns = "http://xml">
~~~~~
]]></expected>, False)
End If
End Sub
<WorkItem(969980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969980")>
<WorkItem(123533, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=123533")>
<Fact>
Public Sub UnaliasedXmlImport_Project()
Dim import = "<xmlns = ""http://xml"">"
Const bug123533IsFixed = False
If bug123533IsFixed Then
CreateCompilationWithMscorlib40({""}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse(import))).VerifyDiagnostics()
Else
Assert.Throws(Of ArgumentException)(Sub() GlobalImport.Parse(import))
End If
End Sub
<WorkItem(1042696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042696")>
<Fact>
Public Sub ParseXmlTrailingNewLinesBeforeDistinct()
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
<!-- -->
Dim y = x
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?>
<x/>
<!-- -->
Distinct
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Distinct"))
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
<!-- -->
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <x/>
Distinct
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Distinct"))
ParseAndVerify(<![CDATA[
Module M
Sub F()
If Nothing Is <?xml version="1.0"?>
<x/>
Then
End If
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_Syntax, "Then"))
ParseAndVerify(<![CDATA[
Module M
Sub F()
If Nothing Is <?xml version="1.0"?>
<x/>
<!-- --> Then
End If
End Sub
End Module
]]>)
End Sub
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports Roslyn.Test.Utilities
Public Class ParseXml
Inherits BasicTestBase
<Fact>
Public Sub ParseElement()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim x = <a>
<b>
aa
</b>
</a>
Dim x = <a b="1" c=<%= 2 %>>hello<!-- comment --><?pi target ?></a>
End Module
]]>)
'Dim x = <a b="1" c=<%= 2 %>></a>
End Sub
<Fact>
Public Sub ParseCDATA()
' Basic xml literal test
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <a><![CDATA[abcde]]></a>" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseEmbeddedExpression()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim y = <a><%= 1 %></a>
End Module
]]>)
End Sub
<Fact(), WorkItem(545537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545537")>
Public Sub ParseNameWhitespace()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim b = <x/>.@<xml:
x>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "x"))
End Sub
<Fact(), WorkItem(529879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529879")>
Public Sub ParseFWPercent()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <x y=<%= 1 ]]>.Value & ChrW(65285) & <![CDATA[>/>
End Module
]]>.Value)
End Sub
<Fact>
Public Sub ParseAccessorSpaceDisallowed()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/>.@ _
x
Dim y = <y/>.@
y
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31146"/>
<error id="30188"/>
</errors>)
End Sub
<Fact(), WorkItem(546401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546401")>
Public Sub ParseAccessorSpaceDisallowed01()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module Program
Dim x = <x/>.<
x>
Dim y = <y/>.<x >
End Module
VB
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "VB"))
End Sub
<WorkItem(531396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531396")>
<Fact()>
Public Sub ParseEmbeddedExpressionAttributeNoSpace()
ParseAndVerify(<![CDATA[
Module M
Private x = <x<%= Nothing %>/>
End Module
]]>)
' Dev11 does not allow this case.
ParseAndVerify(<![CDATA[
Module M
Private x = <x<%="a"%>="b"/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Private x = <x a="b"c="d"/>
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlWhiteSpace, "c"))
ParseAndVerify(<![CDATA[
Module M
Private x = <x a="b"<%= Nothing %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%= Nothing %>a="b"/>
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlWhiteSpace, "a"))
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%= Nothing %><%= Nothing %>/>
End Module
]]>)
' Dev11 does not allow this case.
ParseAndVerify(<![CDATA[
Module M
Private x = <x <%="a"%>="b"<%="c"%>="d"/>
End Module
]]>)
End Sub
<Fact>
Public Sub ParseEmbeddedExpressionAttributeSpace()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M1
Dim x = <x <%= "a" %>=""/>
End Module
]]>)
End Sub
<Fact>
Public Sub BC31169ERR_IllegalXmlStartNameChar_ParseMissingGT()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module m1
dim y1 = <a / >
dim y2 = <a </a>
dim y3 = <a ? ? ?</a>
End Module
]]>, <errors>
<error id="31177"/>
<error id="30636"/>
<error id="31169"/>
<error id="30035"/>
<error id="31169"/>
<error id="31169"/>
</errors>)
End Sub
<WorkItem(641680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641680")>
<Fact>
Public Sub ParseDocumentationComment()
ParseAndVerify(<![CDATA[
''' <summary?
Class C
End Class
]]>)
ParseAndVerify(<![CDATA[
''' <summary?
Class C
End Class
]]>,
VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
</errors>)
End Sub
<WorkItem(641680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641680")>
<Fact>
Public Sub ParseDocumentationComment2()
ParseAndVerify(<![CDATA[
''' <summary/>
Class C
End Class
]]>)
End Sub
<WorkItem(551848, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551848")>
<Fact()>
Public Sub KeywordAndColonInXmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@Sub:a
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@p:Sub
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub Regress12668_NoEscapingOfAttrAxis()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@[Sub]
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@[Sub]:a
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@p:[Sub]
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
End Sub
<Fact>
Public Sub Regress12664_IllegalXmlNameChars()
' Basic xml literal test
ParseAndVerify(<![CDATA[
Module M
Dim x = <a/>.@豈
Dim y = <a/>.@a豈
End Module
]]>, <errors>
<error id="31169"/>
<error id="31170"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a/>.@xml:y
Dim y = <a/>.@xml:y
End Module
]]>, <errors>
<error id="31169"/>
<error id="31170"/>
</errors>)
End Sub
<Fact>
Public Sub BC31159ERR_ExpectedXmlEndEmbedded_ParseMissingEmbbedErrorRecovery()
' Basic xml literal test
ParseAndVerify(<![CDATA[
module m1
sub s
dim x = <a a1=<%=1 <!-- comment --> </a>
end sub
end module
]]>, <errors>
<error id="31159"/>
</errors>)
End Sub
<Fact>
Public Sub BC30636ERR_ExpectedGreater_ParseMissingGreaterTokenInEndElement()
' Basic xml literal test
ParseAndVerify(<![CDATA[
module m1
dim x = <a b="1" c =<%= 2 + 3 %>></a
end module
]]>, <errors>
<error id="30636"/>
</errors>)
End Sub
<Fact>
Public Sub ParseAttributeMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p.@a:b
dim a1=p.
@a:b
end module
]]>)
End Sub
<Fact>
Public Sub ParseElementMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p.<a:b>
dim a2=p.
<a:b>
end module
]]>)
End Sub
<Fact>
Public Sub ParseDescendantMemberAccess()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
dim a1=p...<a:b>
dim a2=p...
<a:b>
end module
]]>)
End Sub
<WorkItem(875151, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyCDATA()
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <![CDATA[]]>" & vbCrLf &
"End Module")
End Sub
<WorkItem(875156, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyPI()
ParseAndVerify("Module m1" & vbCrLf &
"Dim x = <?pi ?>" & vbCrLf &
"Dim y = <?pi?>" & vbCrLf &
"Dim z = <?pi abcde?>" & vbCrLf &
"End Module")
End Sub
<WorkItem(874435, "DevDiv/Personal")>
<Fact>
Public Sub ParseSignificantWhitespace()
ParseAndVerify(<![CDATA[
module m1
dim x =<ns:e>
a <ns:e> <
</ns:e>
</ns:e>
end module
]]>).
VerifyOccurrenceCount(SyntaxKind.XmlTextLiteralToken, 3)
End Sub
<Fact>
Public Sub ParseXmlNamespace()
ParseAndVerify(<![CDATA[
module m1
Dim x = GetXmlNamespace(p)
end module
]]>)
End Sub
<Fact>
Public Sub BC30203ERR_ExpectedIdentifier_ParseDescendantMemberAccessWithEOLError()
' Test attribute member syntax
ParseAndVerify(<![CDATA[
module m1
sub s
dim a1=p..
.<a:b>
end sub
end module
]]>,
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""))
End Sub
<WorkItem(539502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539502")>
<Fact>
Public Sub ParseAttributeWithLeftDoubleQuotationMark()
ParseAndVerify(<![CDATA[
Module M
Dim x = <tag attr=“"/>“/>
End Module
]]>)
End Sub
<WorkItem(539502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539502")>
<Fact>
Public Sub ParseAttributeWithRegularDoubleQuotationMark()
ParseAndVerify(<![CDATA[
Module M
Dim x = <tag attr="abc/>"/>
End Module
]]>)
End Sub
<WorkItem(878042, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeValueSpecialCharacters()
ParseAndVerify(<![CDATA[
module module1
sub main()
dim x1 = <goo attr1="& < > ' ""></goo>
end sub
end module
]]>)
End Sub
<WorkItem(879417, "DevDiv/Personal")>
<Fact>
Public Sub ParsePrologue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <?xml version="1.0" encoding="utf-8"?>
<root/>
End Sub
End Module
]]>)
End Sub
<WorkItem(879562, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeAccessExpression()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <a b="goo" />
Dim y = x.@b
End Sub
End Module
]]>)
End Sub
<WorkItem(879678, "DevDiv/Personal")>
<Fact>
Public Sub BC31163ERR_ExpectedSQuote_ParseAttribute()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <goo attr1='qqq"></>
End Sub
End Module
]]>,
<errors>
<error id="31163"/>
</errors>)
End Sub
<WorkItem(880383, "DevDiv/Personal")>
<Fact>
Public Sub ParseMultilineCDATA()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" Dim x = <![CDATA[" & vbCrLf &
" ]]>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseMultilineCDATAVariousEOL()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" Dim x = <![CDATA[" & vbCrLf &
"abcdefghihjklmn" & vbCr &
" " & vbLf &
" ]]>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<WorkItem(880401, "DevDiv/Personal")>
<Fact>
Public Sub ParseMultilineXComment()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <!--
-->
End Sub
End Module
]]>)
End Sub
<WorkItem(880793, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim x1 = <outer><%= _
<otherXml></otherXml>
%></outer>
End Sub
End Module
]]>)
End Sub
<WorkItem(880798, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlProcessingInstructionAfterDocument()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <?xml version="1.0"?>
<a><?PI target2?></a>
<?PI target?>
End Sub
End Module
]]>)
End Sub
<WorkItem(881535, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlCDATAContainingImports()
ParseAndVerify(
"Module Module1" & vbCrLf &
" Sub Main()" & vbCrLf &
" scenario = <scenario><![CDATA[" & vbCrLf &
"Imports Goo" & vbCrLf &
" ]]></scenario>" & vbCrLf &
" End Sub" & vbCrLf &
"End Module")
End Sub
<WorkItem(881819, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseXmlQuestionMar()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x =<?></?>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
End Sub
<WorkItem(881822, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlUnterminatedXElementStartWithComment()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <
'
Dim y = <
End Sub
End Module
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30636"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30636"/>
<error id="31146"/>
<error id="31177"/>
</errors>)
End Sub
<WorkItem(881823, "DevDiv/Personal")>
<Fact>
Public Sub BC31175ERR_DTDNotSupported()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim a2 = <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, world!</greeting>
End Sub
End Module
]]>,
<errors>
<error id="31175"/>
</errors>)
End Sub
<WorkItem(881824, "DevDiv/Personal")>
<Fact>
Public Sub BC31172ERR_EmbeddedExpression_Prologue()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <?xml version="1.0" encoding=<%= encoding %>?><element/>
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
</errors>
)
End Sub
<WorkItem(881825, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeEmbeddedExpressionImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <subnode att=
<%=
42
%>
/>
End Sub
End Module
]]>)
End Sub
<WorkItem(881828, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlNamespaceImports()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns="http://microsoft.com">
]]>)
End Sub
<WorkItem(881829, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionLambdaImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim k = <xml><%= Function()
Return {1
}
End Function %>
</xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(881820, "DevDiv/Personal")>
<WorkItem(882380, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlElementContentEntity()
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim x = <element><</>
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Public Module Module1
Public Sub Main()
Dim buildx = <xml><></xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(882421, "DevDiv/Personal")>
<Fact>
Public Sub ParseAttributeAccessorBracketed()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns = "goo">
Imports <xmlns:n-s- = "goo2">
Module Module1
Sub Main()
Dim ele3 = <ns:e/>
ele3.@<n-s-:A-A> = <e><%= "hello" %></e>.Value.ToString()
End Sub
End Module
]]>)
End Sub
<WorkItem(882460, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeAccessorInWith()
ParseAndVerify(<![CDATA[
Module Module1
Class Customer : Inherits XElement
Sub New()
MyBase.New(<customer/>)
End Sub
End Class
Sub Main()
Dim oldCust = <customer name="Sally"/>
With oldCust
Dim newCust As New Customer With {.Name = .@name}
End With
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub BC31178ERR_ExpectedSColon()
Dim tree = Parse(<![CDATA[
Imports <xmlns:p="0">
Module M
Private F = <x><Z</x>
End Module
]]>)
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC31178: Expected closing ';' for XML entity.
Imports <xmlns:p="0">
~~~~~
BC31178: Expected closing ';' for XML entity.
Private F = <x><Z</x>
~~~~~
]]></errors>)
End Sub
<WorkItem(882874, "DevDiv/Personal")>
<Fact>
Public Sub BC31178ERR_ExpectedSColon_ParseXmlEntity()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1="&"></goo>
End Sub
End Module
]]>,
<errors>
<error id="31178"/>
</errors>)
End Sub
<Fact>
Public Sub BC31166ERR_StartAttributeValue_ParseXmlAttributeUnquoted()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1=before&after></goo>
End Sub
End Module
]]>,
<errors>
<error id="31166"/>
</errors>)
End Sub
<Fact>
Public Sub BC31155ERR_QuotedEmbeddedExpression_ParseXmlAttribute()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim z = <goo attr1="<%= %>"></goo>
End Sub
End Module
]]>,
<errors>
<error id="31155"/>
</errors>)
End Sub
<WorkItem(882898, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionXmlAccessorLineContinuation()
ParseAndVerify(<![CDATA[
Imports <xmlns:ns="lower">
Module Module1
Sub Main()
Dim A1 = <ns:book>
<title name="Debug Applications">
<award>
<ns:award ns:year="1998" name="MS award"/>
<ns:award ns:year="1998" name="Peer Recognition"/>
</award>
</title>
</ns:book>
Dim frag = <fragment>
<%= From i In A1.<ns:book> _
.<title> _
Select i.@name 'qqq
%>
</fragment>
End Sub
End Module
]]>)
End Sub
<WorkItem(883277, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeEmbeddedExpressionLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <e a=
<%= 3 %>></e>
End Sub
End Module
]]>)
End Sub
<WorkItem(883619, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = New Object() {<?xml version="1.0"?>
<%= <e/> %>, _
<?xml version="1.0"?>
<%= <e/> %> _
}
End Sub
End Module
]]>)
End Sub
<WorkItem(883620, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEntityNumericCharacterReference()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim el3 = <element>Ӓ < F</element>
End Sub
End Module
]]>)
End Sub
<WorkItem(883626, "DevDiv/Personal")>
<Fact>
Public Sub BC31153ERR_MissingVersionInXmlDecl_ParseXmlEmbeddedExpressionInPrologue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <?xml <%= New XAttribute("some", "1.0") %> version="1.0" ?><e/>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31172"/>
<error id="30249"/>
<error id="31153"/>
</errors>)
End Sub
<WorkItem(883628, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlNameRem()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim A1 As XElement = <Rem />
Dim x = A1.<Rem>
End Sub
End Module
]]>)
End Sub
<WorkItem(883651, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionContainsQuery()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i3 = <xml>
<%=
From el
In {1, 2, 3}
Select (<node><%= el %></node>)
%>
</xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(883734, "DevDiv/Personal")>
<Fact>
Public Sub BC31160ERR_ExpectedXmlEndPI_ParseXmlPrologueInQuery()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x31 = From i In {}
Select <?xml version="1.0">
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(887785, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlImplicitExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim xml =
_
<xml></xml>
End Sub
End Module
]]>)
End Sub
<WorkItem(887792, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlElementCharDataSibling()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim b = <fragment>
<element></element>
Sometext
</fragment>
End Sub
End Module
]]>)
End Sub
<WorkItem(887798, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlGetXmlNamespaceRem()
ParseAndVerify(<![CDATA[
Imports <xmlns:Rem = "http://testcase">
Module Module1
Sub Main()
Dim y = GetXmlNamespace(Rem) + "localname"
End Sub
End Module
]]>)
End Sub
<WorkItem(888542, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlDocumentStopsParsingXml()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Dim x_XML = <?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact>
<name><Prefix>Mr</Prefix>Adam Braden</name>
<phone>215 123456</phone>
</contact>
</contacts>
End Sub
End Module
]]>)
End Sub
<WorkItem(894127, "DevDiv/Personal")>
<Fact()>
Public Sub BC30001ERR_ParseXmlDocumentWithExpressionBody_NoParseError()
ParseAndVerify(<![CDATA[
Dim b = <?xml version="1.0"?>
<%= <e><%= j.e & i.e %></e> %>
]]>)
End Sub
<WorkItem(893969, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlPrecededByExplicitLineContinuation()
ParseAndVerify(<![CDATA[
Namespace DynLateSetLHS010
Friend Module DynLateSetLHS010mod
Sub DynLateSetLHS010()
Dim el = _
<name1>
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
<error id="31151"/>
<error id="30026"/>
<error id="30625"/>
<error id="30626"/>
</errors>)
End Sub
<WorkItem(893973, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlPrecededByExplicitLineContinuationLine()
ParseAndVerify(<![CDATA[
Namespace DynLateSetLHS010
Friend Module DynLateSetLHS010mod
Sub DynLateSetLHS010()
Dim el =
_
<name1>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndNamespace, "Namespace DynLateSetLHS010"),
Diagnostic(ERRID.ERR_ExpectedEndModule, "Friend Module DynLateSetLHS010mod"),
Diagnostic(ERRID.ERR_EndSubExpected, "Sub DynLateSetLHS010()"),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_"),
Diagnostic(ERRID.ERR_StandaloneAttribute, ""),
Diagnostic(ERRID.ERR_LocalsCannotHaveAttributes, "<name1>"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""))
End Sub
<WorkItem(897813, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlExplicitLineContinuationLineFollowedByLessThan()
ParseAndVerify(<![CDATA[
' This isn't really xml
Dim el =
_
< ]]>,
<errors>
<error id="30201"/>
<error id="30999"/>
<error id="30203"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(898451, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseXmlErrorBeginningWithLessThanGreaterThan()
ParseAndVerify(<![CDATA[
Module TestModule
Sub Main()
Dim A = <>
<ns:book collection="library">
<%= <>
<ns:award ns:year="1998" name="Booker Award"/>
</> %>
</ns:book>
<%= returnXml(<args></args>, str) %>
</>
End Sub
End Module
]]>,
<errors>
<error id="31146"/>
<error id="31146"/>
</errors>)
End Sub
<WorkItem(885888, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlErrorNameStartingWithExclamation()
ParseAndVerify(<root>
Class Class1
Sub Main()
Dim y2 = <! [CDATA[]]>
'</> 'Required for error recovery
End Sub
End Class
</root>.Value,
<errors>
<error id="31146"/>
<error id="31169"/>
<error id="30636"/>
<error id="31169"/>
<error id="31170"/>
</errors>)
End Sub
<WorkItem(889091, "DevDiv/Personal")>
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingPercentGreaterThanToken()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <abc def=<%=baz >
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingExpression()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <%=
End Sub
End Class
]]>,
Diagnostic(ERRID.ERR_EmbeddedExpression, "<%="),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""))
End Sub
<WorkItem(889091, "DevDiv/Personal")>
<Fact()>
Public Sub BC31151ERR_MissingXmlEndTag_ParseXmlEmbeddedExpressionMissingPercentGreaterThanTokenWithColon()
ParseAndVerify(<![CDATA[
Class C1
Sub S1()
Dim x = <abc bar=<%=baz >:
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="31159"/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(899741, "DevDiv/Personal")>
<Fact>
Public Sub ParseIncompleteProcessingInstruction()
ParseAndVerify(<![CDATA[
Dim y As Object() = New Object() {<goo/>, <?pi
]]>,
<errors>
<error id="30370"/>
<error id="31160"/>
</errors>)
End Sub
<WorkItem(899919, "DevDiv/Personal")>
<Fact>
Public Sub ParseIncompleteXmlDoc()
ParseAndVerify(<![CDATA[
Dim rss = <?xml vers]]>,
<errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(900238, "DevDiv/Personal")>
<Fact>
Public Sub ParseGetXmlNamespace()
ParseAndVerify(<![CDATA[
Dim ns = GetXmlNamespace(
]]>,
<errors>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(900250, "DevDiv/Personal")>
<Fact>
Public Sub ParseExprHoleInXMLDoc()
ParseAndVerify(<![CDATA[
Sub New()
MyBase.New(<?xml version="1.0" encoding=<%=
]]>,
<errors>
<error id="30026"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(903139, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrXmlDoc()
ParseAndVerify(<![CDATA[Dim x1 = <?xml q ?>]]>,
<errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(903556, "DevDiv/Personal")>
<Fact>
Public Sub BC31198ERR_XmlEndCDataNotAllowedInContent_ParseCDataCloseTagInContent()
'Could not use CDATA since code involves CDATA close tag
Dim code = "Module M1" & vbCrLf &
"Dim x = <doc>]]></doc>" & vbCrLf &
"End Module"
ParseAndVerify(code,
<errors>
<error id="31198"/>
</errors>)
End Sub
<WorkItem(903557, "DevDiv/Personal")>
<Fact>
Public Sub ParseBadXmlDocument()
ParseAndVerify(<![CDATA[
Module M1
Dim x = <?xml name value ?>
<test/>
End Module
]]>, <errors>
<error id="31154"/>
<error id="30249"/>
<error id="31153"/>
</errors>)
End Sub
<WorkItem(903564, "DevDiv/Personal")>
<Fact>
Public Sub BC31171ERR_IllegalXmlCommentChar()
ParseAndVerify(<![CDATA[
Module M1
Dim x = <!-- a -- a -->
End Module
]]>, <errors>
<error id="31171"/>
</errors>)
End Sub
<WorkItem(903592, "DevDiv/Personal")>
<Fact>
Public Sub BC31173ERR_ExpectedXmlWhiteSpace_ParseAttributeSpace()
ParseAndVerify(<![CDATA[
Module M1
Dim d =
<a b="c"d="e"/>
End Module
]]>, <errors>
<error id="31173"/>
</errors>)
End Sub
<WorkItem(903586, "DevDiv/Personal")>
<Fact>
Public Sub BC31174ERR_IllegalProcessingInstructionName()
ParseAndVerify(<![CDATA[
Module M1
Dim f = <?xmL?>
End Module
]]>, <errors>
<error id="31174"/>
</errors>)
End Sub
<WorkItem(903938, "DevDiv/Personal")>
<Fact>
Public Sub ParseDeclaration_ERR_ExpectedEQ()
ParseAndVerify(<![CDATA[
Module M1
Dim f =
<?xml version eq '1.0' ?>
<doc/>
End Module
]]>, <errors>
<error id="30249"/>
</errors>)
End Sub
<WorkItem(903951, "DevDiv/Personal")>
<Fact>
Public Sub BC31177ERR_IllegalXmlWhiteSpace_ParseXmlNameStartsWithNewLine()
ParseAndVerify(<![CDATA[
Module M1
Dim x1 = < doc/>
Dim x2 = <
doc/>
dim x3 = < a :b />
dim x4 = <a: b = "1" />
dim x5=<a:b></ a : b >
dim x6=<a b : c="1" />
end module
]]>, Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "b"),
Diagnostic(ERRID.ERR_ExpectedXmlName, ""),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "b"),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "),
Diagnostic(ERRID.ERR_ExpectedXmlName, "c"))
End Sub
<Fact>
Public Sub BC31177ERR_IllegalXmlWhiteSpace_ParseBracketedXmlQualifiedName()
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@< a>
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@< p:a>
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@<a >
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = x.@<p:a >
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
</errors>)
End Sub
<WorkItem(903972, "DevDiv/Personal")>
<Fact>
Public Sub BC31150ERR_MismatchedXmlEndTag()
ParseAndVerify(<![CDATA[
Module M1
Dim d =
<doc></DOC>
End Module
]]>, <errors>
<error id="31150"/>
<error id="31151"/>
</errors>)
End Sub
<WorkItem(903986, "DevDiv/Personal")>
<Fact>
Public Sub BC31181ERR_InvalidAttributeValue1_BadVersion()
ParseAndVerify(<![CDATA[
Module M1
Dim f =
<?xml version="1.0?"?><e></e>
End Module
]]>, <errors>
<error id="31181"/>
</errors>)
End Sub
<WorkItem(889870, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlRequiresParensNotReported()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim f = From e As XProcessingInstruction In <?xpi Val=2?>
End Sub
End Class
]]>)
End Sub
<WorkItem(889866, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEntityReferenceErrorNotExpected()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim x3 = <goo attr1="x < A"></goo>
End Sub
End Class
]]>)
End Sub
<WorkItem(889865, "DevDiv/Personal")>
<Fact>
Public Sub BC30026ERR_EndSubExpected_ParseMoreErrorExpectedGreater()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
dim x1 = <goo attr1='qqq"></>
Sub
End Class
]]>,
<errors>
<error id="30026"/>
<error id="31163"/>
<error id="30289"/>
<error id="30026"/>
<error id="30203"/>
</errors>)
End Sub
<WorkItem(889898, "DevDiv/Personal")>
<Fact>
Public Sub ParseMoreErrorsExpectedLTAndExpectedXmlEndPI()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
#If True Then
Dim x31 = From i In (<ns:e <%= <ns:e><%= ns & "hello" %></ns:e> %>></ns:e>.<ns:e>) _
Where i.Value <> (<<%= <ns:e><%= ns %></ns:e>.Name %>><%= ns %></>.Value) _
Select <?xml version="1.0">
'</> 'Required for error recovery
#Else
'COMPILERWARNING : 42019, "ns & \"hello\""
#End If
End Sub
End Class
]]>,
<errors>
<error id="31146"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(885799, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar_ParseErrorMismatchSyntaxVSExpectedGreater()
ParseAndVerify(<![CDATA[
Class Class1
Sub Scenario1()
Dim b = new integer? << <goo/> << <what?/>
End Sub
End Class
]]>,
<errors>
<error id="31170"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(885790, "DevDiv/Personal")>
<Fact>
Public Sub BC31150ERR_MismatchedXmlEndTag_ParseErrorMismatchExpectedGreaterVSSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Sub Main()
Dim x = <e a='<%="v"%>'></a>
End Sub
End Class
]]>,
<errors>
<error id="31151"/>
<error id="31155"/>
<error id="31150"/>
</errors>)
End Sub
<WorkItem(924043, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionInXmlName()
ParseAndVerify(<![CDATA[
Module TestModule
Sub Main()
Dim B = <root>
<<%= <abc><root>name</root></abc>...<root>.value %>></>
</root>
End Sub
End Module
]]>)
End Sub
<WorkItem(925953, "DevDiv/Personal")>
<WorkItem(927711, "DevDiv/Personal")>
<Fact>
Public Sub BC31165ERR_ExpectedLT_ParseXmlErrorRecoveryMissingEnd()
ParseAndVerify(<![CDATA[
Module TestModule
dim x=<a><b></a>
End Module
]]>, <errors>
<error id="31151"/>
<error id="31165"/>
<error id="31146"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(926593, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithNamespace()
ParseAndVerify(<![CDATA[
Namespace ExpandoContext02
Friend Module ExpandoContext02mod
Sub ExpandoContext02()
Dim x10 = <?xml version="1.0"?><%= <e <%= New XAttribute("a", "v") %> <%= <e ns:a=<%= "v" %> <%= "b" %>="v"/> %>></e> %>
Dim a = <e <%= XName.Get("a", GetXmlNamespace(ns).ToString) %>="v"><ns:EE-E>SUCCESS</ns:EE-E></e>
End Sub
End Module
End Namespace
]]>)
End Sub
<WorkItem(926595, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlEmbeddedExpressionWithStatement()
ParseAndVerify(<![CDATA[
Module Test
Sub Method()
Dim b3 = <<%= "e" %> <%= New With {New With {New With {New With {(<e><%= 1 %></e>.Value << 3 >> 1).ToString.ToCharArray}.ToCharArray}.ToCharArray}.ToCharArray}.ToCharArray %>/>
End Sub
End Module
]]>)
End Sub
<WorkItem(926595, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrorXmlEmbeddedExpressionInvalidValue()
ParseAndVerify(<![CDATA[
Module Test
Sub Method()
Dim x7 = <a><%= Class %></a>
Dim x71 = <a><<%= Function %>/></a>
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30035"/>
<error id="30199"/>
<error id="30198"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(527094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527094")>
<WorkItem(586871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586871")>
<Fact>
Public Sub BC31197ERR_FullWidthAsXmlDelimiter_ParseXmlStart()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = <xml></xml>
Dim y =<STAThread/>
Dim z =<!-- Not a comment --!>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"))
'Note that the first "<" character above
'is a full-width unicode character (not ascii).
End Sub
<WorkItem(927138, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlLargeNumberOfTrailingNewLines()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Try
Dim d =
<?xml version="1.0"?>
<root/>
Catch ex as Exception
End Try
End Sub
End Module
]]>)
End Sub
<WorkItem(927387, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlAttributeValueThatStartsOnNewLine()
ParseAndVerify(<![CDATA[
Module M1
Dim doc =
<?xml
version
=
'1.0'
?>
<doc/>
End Module
]]>)
End Sub
<WorkItem(927823, "DevDiv/Personal")>
<Fact>
Public Sub BC31154ERR_IllegalAttributeInXmlDecl_ParseBadXmlWithFullWidthContent()
ParseAndVerify(<![CDATA[
Module Module2
Sub Main()
Dim code = <?xml version="1.0"?>
<xml ver="1.0" ver0=`1.0' ver1=`1.0` ver2='1.0'>
<<%="xml"%> <%="xml"%>=<%="xml"%>/>
<%= <!--version="1.0"--><?ver?> <![CDATA[version="1.0"]]> %>
</>
End Sub
End Module]]>,
<errors>
<error id="31154"/>
<error id="31169"/>
<error id="30249"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31169"/>
<error id="31153"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
'Note that the characters after "<?xml " upto and including "</>" above
'are full-width unicode characters (not ascii).
End Sub
<WorkItem(927834, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar_ParseXmlWithFullWidthContentInEmbeddedExpression()
'TODO: This is a change in behavior from Dev10.
'Please move this test to BreakingChanges.vb if this is a change that we want to keep.
ParseAndVerify(<![CDATA[
Module Module2
Sub Main()
Dim code = <xml ver="hi"><<%="xml"%>/></>
End Sub
End Module]]>, <errors>
<error id="31169"/>
</errors>)
'Note that the characters starting from <%= to %> (both inclusive) above
'are full-width unicode characters (not ascii).
End Sub
<WorkItem(928408, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmbeddedXMLWithCRLFInTag()
ParseAndVerify(<![CDATA[Dim x12 = <e><%= <e
]]>, <errors>
<error id="31151"/>
<error id="31151"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(930274, "DevDiv/Personal")>
<Fact>
Public Sub ParseLegalValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim doc =
<?xml version='1.0' standalone='yes'?><e/>
Dim doc2 =
<?xml version='1.0' standalone='no'?><e/>
End Module]]>)
End Sub
<WorkItem(930256, "DevDiv/Personal")>
<Fact>
Public Sub BC31182ERR_InvalidAttributeValue2_ParseEmptyValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim x = <?xml version="1.0" standalone=''?><doc/>
End Module
]]>,
<errors>
<error id="31182"/>
</errors>)
End Sub
<WorkItem(930757, "DevDiv/Personal")>
<Fact>
Public Sub BC31182ERR_InvalidAttributeValue2_ParseBadValueForStandaloneAttributeInPrologue()
ParseAndVerify(<![CDATA[Module M1
Dim doc =
<?xml version='1.0' standalone='YES'?><e/>
Dim doc2 =
<?xml version='1.0' standalone='nO'?><e/>
End Module]]>, <errors>
<error id="31182"/>
<error id="31182"/>
</errors>)
End Sub
<WorkItem(537183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537183")>
<WorkItem(930327, "DevDiv/Personal")>
<Fact>
Public Sub BC31146ERR_ExpectedXmlName_ParseBadEncodingAttributeInPrologue()
ParseAndVerify(<![CDATA[module m1
dim x = <?xml version="1.0" "UTF-8"encoding=?>
<!--* wrong ordering in above EncodingDecl *--><root/>
end module
module m2
dim x = <?xml version="1.0"encoding="UTF-8"?>
<!--* missing white space in above EncodingDecl *-->
<root/>
end module]]>, <errors>
<error id="31146" message="XML name expected." start="38" end="39"/>
<error id="31173" message="Missing required white space." start="161" end="169"/>
</errors>)
End Sub
<WorkItem(930330, "DevDiv/Personal")>
<Fact>
Public Sub BC30037ERR_IllegalChar_ParseIllegalXmlCharacters()
ParseAndVerify("Module M1" & vbCrLf &
"Dim doc = " & vbCrLf &
"<?xml version=""1.0""?><doc></doc>" & vbCrLf &
"End Module" & vbCrLf &
vbCrLf &
"Module M2" & vbCrLf &
"Dim frag = " & vbCrLf &
"<e><doc></doc></>" & vbCrLf &
"End Module", <errors>
<error id="30037"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(538550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538550")>
<WorkItem(538551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538551")>
<Fact>
Public Sub ParseXmlStringIncludingSmartQuotes()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr=""" & ChrW(8216) & """ />" & vbCrLf &
"Dim x2 = <tag attr=""" & ChrW(8217) & """ />" & vbCrLf &
"Dim x3 = <tag attr=""" & ChrW(8220) & """ />" & vbCrLf &
"Dim x4 = <tag attr=""" & ChrW(8221) & """ />" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseXmlSmartSingleString()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr= " & ChrW(8216) & "text" & ChrW(8216) & "/>" & vbCrLf &
"Dim x2 = <tag attr= " & ChrW(8216) & "text" & ChrW(8217) & "/>" & vbCrLf &
"Dim x3 = <tag attr= " & ChrW(8217) & "text" & ChrW(8216) & "/>" & vbCrLf &
"Dim x4 = <tag attr= " & ChrW(8217) & "text" & ChrW(8217) & "/>" & vbCrLf &
"End Module")
End Sub
<Fact>
Public Sub ParseXmlSmartDoubleString()
ParseAndVerify(
"Module M1" & vbCrLf &
"Dim x1 = <tag attr= " & ChrW(8220) & "text" & ChrW(8220) & "/>" & vbCrLf &
"Dim x2 = <tag attr= " & ChrW(8220) & "text" & ChrW(8221) & "/>" & vbCrLf &
"Dim x3 = <tag attr= " & ChrW(8221) & "text" & ChrW(8220) & "/>" & vbCrLf &
"Dim x4 = <tag attr= " & ChrW(8221) & "text" & ChrW(8221) & "/>" & vbCrLf &
"End Module")
End Sub
<WorkItem(544979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544979")>
<Fact()>
Public Sub ParseEmbeddedLambda()
ParseAndVerify(<![CDATA[
Module Program
Dim x = <x <%= Sub() Return %>/>
End Module
]]>.Value)
End Sub
<WorkItem(538241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538241")>
<Fact>
Public Sub ParseXmlMemberFollowedByWSColon()
Dim tree = ParseAndVerify(<![CDATA[
Module A
Sub Main()
Dim x = <x/>.@x : Console.WriteLine()
End Sub
End Module
]]>.Value)
Dim main = tree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1)
Dim stmt1 = main.ChildNodesAndTokens()(1)
Dim stmt2 = main.ChildNodesAndTokens()(2)
Dim colon = stmt1.ChildNodesAndTokens().LastOrDefault().GetTrailingTrivia().Last
Assert.Equal(colon.Kind, SyntaxKind.ColonTrivia)
Assert.Equal(stmt2.Kind(), SyntaxKind.ExpressionStatement)
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(stmt2.AsNode, ExpressionStatementSyntax).Expression.Kind)
Dim exprStmt = TryCast(stmt2.AsNode, ExpressionStatementSyntax)
Dim invocExp = TryCast(exprStmt.Expression, InvocationExpressionSyntax)
Dim memAccess = TryCast(invocExp.Expression, MemberAccessExpressionSyntax)
Assert.Equal(memAccess.Expression.ToString, "Console")
Assert.Equal(memAccess.Name.ToString, "WriteLine")
End Sub
<WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")>
<Fact()>
Public Sub Bug7954()
' 0123456789ABC
Dim code = <![CDATA[Dim=<><%=">
<]]>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(code)
Assert.Equal(code, tree.GetRoot().ToString())
End Sub
<WorkItem(545076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545076")>
<Fact()>
Public Sub WhitespaceInClosingTag()
ParseAndVerify(<![CDATA[
Module M1
Sub Main
Dim x = <goo>< /goo>
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, "< /"),
Diagnostic(ERRID.ERR_ExpectedLT, ""))
End Sub
<WorkItem(529395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529395")>
<Fact()>
Public Sub Bug12644()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() If True Then Else %></x>
End Module
]]>)
End Sub
<WorkItem(544399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544399")>
<Fact()>
Public Sub BrokenEndElementStartInXmlDoc()
ParseAndVerify(<![CDATA[
''' </
Module M
End Module
]]>,
VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
Diagnostic(ERRID.WRN_XMLDocParseError1, "</").WithArguments("XML end element must be preceded by a matching start element."),
Diagnostic(ERRID.WRN_XMLDocParseError1, "").WithArguments("'>' expected."))
End Sub
<WorkItem(547320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547320")>
<WorkItem(548952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548952")>
<Fact()>
Public Sub Bug18598()
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= F(End
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30201"/>
<error id="30198"/>
<error id="31159"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(+
Return
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(548996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548996")>
<Fact()>
Public Sub Bug548996()
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= x +
Return
%>/>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_MissingXmlEndTag, <![CDATA[<<%= x +
Return
%>]]>),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_Syntax, "Return"),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""),
Diagnostic(ERRID.ERR_IllegalXmlStartNameChar, "%").WithArguments("%", "&H25"),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ""))
ParseAndVerify(<![CDATA[
Module M
Private x = <<%= x +
Return : %>/>
]]>,
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_MissingXmlEndTag, <![CDATA[<<%= x +
Return : %>]]>),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_Syntax, "Return"),
Diagnostic(ERRID.ERR_ExpectedXmlEndEmbedded, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ":"),
Diagnostic(ERRID.ERR_IllegalXmlStartNameChar, "%").WithArguments("%", "&H25"),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, ""))
End Sub
<WorkItem(575763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575763")>
<Fact()>
Public Sub Bug575763()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
%>/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31169"/>
<error id="30249"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/> %>
c=""/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <b/>
c=""/>
End Module
]]>,
<errors>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
End Sub
<WorkItem(575780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575780")>
<Fact()>
Public Sub Bug575780()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Function() :
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() :
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() : Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Return :
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else :
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else If False Then Return Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else If False Then Return Else : Return
End Module
]]>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then Else If True Then :
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then If True Then Else :
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If True Then Else If True Then Else :
End Module
]]>)
End Sub
''' <summary>
''' As above but with lambda inside embedded expression.
''' </summary>
<WorkItem(575780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575780")>
<Fact()>
Public Sub Bug575780_EmbeddedExpression()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <<%= Sub() : Return %>/>
End Sub
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026" message="'End Sub' expected."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <<%= Sub() Return : %>/>
End Sub
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026" message="'End Sub' expected."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Return : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Return : Return %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else : %>/>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31169"/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else Return : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else Return : Return %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If False Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else If False Then Return Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then Else If False Then Return Else : Return %>/>
End Module
]]>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
' Dev11: no errors.
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then Else If True Then : %>/>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="30081"/>
<error id="30205"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636" message="'>' expected."/>
<error id="31165"/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then If True Then Else : %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <<%= Sub() If True Then If True Then Else If True Then Else : %>/>
End Module
]]>)
End Sub
<WorkItem(577617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577617")>
<Fact()>
Public Sub Bug577617()
ParseAndVerify(String.Format(<source>
Module M
Dim x = {0}x/>
End Module
</source>.Value, FULLWIDTH_LESS_THAN_SIGN),
Diagnostic(ERRID.ERR_FullWidthAsXmlDelimiter, "<"))
End Sub
<WorkItem(611206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611206")>
<Fact()>
Public Sub Bug611206()
ParseAndVerify(<![CDATA[
Module M
Dim x = <!DOCTYPE
End Module
]]>,
<errors>
<error id="31175" message="XML DTDs are not supported."/>
</errors>)
End Sub
<WorkItem(602208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602208")>
<Fact()>
Public Sub Bug602208()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<!-- -->
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
) %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root/>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root>
</root>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root></>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<%= <root/> %>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
End Sub
<WorkItem(598156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598156")>
<Fact()>
Public Sub Bug598156()
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<!-- -->
%>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= <?xml version="1.0"?>
<b/>
<?p?>.ToString() %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<!-- -->
)
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
) %>/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0"?>
<b/>
, Nothing)
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <a <%= F(<?xml version="1.0"?>
<b/>
, Nothing) %>/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30198" message="')' expected."/>
<error id="31159"/>
<error id="30636"/>
<error id="31169"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?><x/>
Dim y = <?xml version="1.0"?><y/>
End Module
]]>)
End Sub
<WorkItem(598799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598799")>
<Fact()>
Public Sub Bug598799()
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <x/>
Distinct
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/>
' Comment
Distinct
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim q = From x In ""
Select <?xml version="1.0"?>
<x/> ' Comment
Distinct
End Module
]]>)
End Sub
<WorkItem(601050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601050")>
<Fact()>
Public Sub Bug601050()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If False Then Else
Dim y = <x/> %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<WorkItem(601899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601899")>
<Fact()>
Public Sub Bug601899()
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <%= Nothing %>
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <?xml version="1.0"?><%= Nothing %>
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <!--
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Function F(
Return <![CDATA[
End Function
End Module
</source>.Value,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function F(
Return <? :
End Function
End Module
]]>,
<errors>
<error id="30183" message="Keyword is not valid as an identifier."/>
<error id="30198" message="')' expected."/>
</errors>)
End Sub
<Fact()>
Public Sub DocumentWithTrailingMisc()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root/>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root>
</root>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<root></>
Select x
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim q = From c In ""
Let x = <?xml version="1.0"?>
<%= <root/> %>
Select x
End Sub
End Module
]]>)
End Sub
<WorkItem(607253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607253")>
<Fact()>
Public Sub GetXmlNamespaceErrors()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace :
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( :
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y:
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y :
End Module
]]>,
<errors>
<error id="30198" message="')' expected."/>
</errors>)
' Dev11 reports BC30199: "'(' expected."
' although that seems unnecessary.
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace (y)
End Module
]]>)
End Sub
<WorkItem(607352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607352")>
<Fact()>
Public Sub GetXmlNamespaceErrors_2()
ParseAndVerify(<![CDATA[
Imports <xmlns:y="">
Module M
Dim x = GetXmlNamespace
(y)
End Module
]]>,
<errors>
<error id="30199" message="'(' expected."/>
<error id="30035" message="Syntax error."/>
</errors>)
End Sub
<WorkItem(607560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607560")>
<Fact()>
Public Sub GetXmlNamespaceErrors_3()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( y)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(y )
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( )
End Module
]]>)
End Sub
<WorkItem(610345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610345")>
<Fact()>
Public Sub Bug610345()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = <%= CBool(
Return
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30201" message="Expression expected."/>
<error id="30198"/>
<error id="30035"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%=
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
M(<<%=
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30026"/>
<error id="31151"/>
<error id="30201" message="Expression expected."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F( _
#Const c = 0
) %></>
End Module
]]>,
<errors>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x </x>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $ _
REM Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (<%= F() )
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="31159"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (<%= F() _
)
End Module
]]>,
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="31159"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x
x = <%= F() :::
End Sub
End Module
]]>,
<errors>
<error id="31172"/>
<error id="31159"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $:
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x $ 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30037"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x %>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x %> :
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x) $ REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(x) $ _
REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= {1, 2 3
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30370"/>
<error id="30370"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= New Object()(1
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32014"/>
<error id="30198"/>
<error id="30987"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function(Of T
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36674"/>
<error id="32065"/>
<error id="30199"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function(Of T)
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36674"/>
<error id="32065"/>
<error id="30199"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= If(Nothing) 'Comment
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="33104"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= If(1, 2 3 REM
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="30198"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= F(y z
) %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="32017"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= F(y z
)
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() a!b c %>
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="30800"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Sub() a!b c %> :
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="31151"/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="30800"/>
<error id="32017"/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(671111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/671111")>
<Fact()>
Public Sub Bug671111()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
<y>
<z></z / </y>
</x>
End Module
]]>,
<errors>
<error id="30636"/>
<error id="30636"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x>
<y>
<z></z / </y>
</x>
End Module
]]>,
<errors>
<error id="30636"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(673558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673558")>
<Fact()>
Public Sub Bug673558()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><
<]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31151"/>
<error id="31146"/>
<error id="30636"/>
<error id="31151"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><
REM]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31151"/>
<error id="31177"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(673638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673638")>
<Fact()>
Public Sub NotLessThan_Imports()
ParseAndVerify(<![CDATA[
Imports <%=xmlns="">
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <%=>
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <%=%>
]]>,
<errors>
<error id="31165"/>
<error id="31169"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports </xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports </>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <?xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <?>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!--xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!-->
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!---->
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <![CDATA[xmlns="">
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <![CDATA[>
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify("Imports <![CDATA[]]>",
<errors>
<error id="30203"/>
<error id="30037"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!DOCTYPExmlns="">
]]>,
<errors>
<error id="31165"/>
<error id="31175"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <!DOCTYPE>
]]>,
<errors>
<error id="31165"/>
<error id="31175"/>
</errors>)
End Sub
<Fact()>
Public Sub NotLessThan_BracketedXmlName()
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<%= y %>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<%= y %>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.</y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@</y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<?y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<?y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<!--y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<!--y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<![CDATA[y>
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<![CDATA[y>
End Module
]]>,
<errors>
<error id="31146"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.<!DOCTYPE>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<!DOCTYPE>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(674567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674567")>
<Fact()>
Public Sub Bug674567()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= <p:
y a=""/>
End Module
]]>,
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="31177"/>
<error id="31146"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= <p:
End Module
]]>,
<errors>
<error id="31172"/>
<error id="31151"/>
<error id="31177"/>
<error id="31146"/>
<error id="30636"/>
<error id="31165"/>
<error id="30636"/>
<error id="31159"/>
</errors>)
End Sub
<Fact()>
Public Sub XmlNameTokenPossibleKeywordKind()
Const sourceTemplate = "
Module M
Dim x = <{0}:
y a=""/>
End Module
"
Const squiggleTemplate = "<{0}:
y a=""/>
End Module
"
Dim commonExpectedErrors =
{
Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M"),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, "
"),
Diagnostic(ERRID.ERR_ExpectedXmlName, "y"),
Diagnostic(ERRID.ERR_ExpectedQuote, ""),
Diagnostic(ERRID.ERR_ExpectedLT, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "")
}
Dim tree1 = Parse(String.Format(sourceTemplate, "e"))
tree1.GetDiagnostics().Verify(commonExpectedErrors.Concat({Diagnostic(ERRID.ERR_MissingXmlEndTag, String.Format(squiggleTemplate, "e"))}).ToArray())
Dim tree2 = Parse(String.Format(sourceTemplate, "ee"))
tree2.GetDiagnostics().Verify(commonExpectedErrors.Concat({Diagnostic(ERRID.ERR_MissingXmlEndTag, String.Format(squiggleTemplate, "ee"))}).ToArray())
Dim getPossibleKeywordKind = Function(x As XmlNameSyntax) DirectCast(x.Green, InternalSyntax.XmlNameSyntax).LocalName.PossibleKeywordKind
Dim kinds1 = tree1.GetRoot().DescendantNodes().OfType(Of XmlNameSyntax).Select(getPossibleKeywordKind)
Assert.NotEmpty(kinds1)
AssertEx.All(kinds1, Function(k) k = SyntaxKind.XmlNameToken)
Dim kinds2 = tree2.GetRoot().DescendantNodes().OfType(Of XmlNameSyntax).Select(getPossibleKeywordKind)
Assert.Equal(kinds1, kinds2)
End Sub
<Fact()>
Public Sub TransitionFromXmlToVB()
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace( ' comment
End Module
]]>,
<errors>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = GetXmlNamespace(p
End Module
]]>,
<errors>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <xmlns:p=""
Module M
End Module
]]>,
<errors>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x.@<p ' comment
End Module
]]>,
<errors>
<error id="31177"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding=<%=
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding=<%=""%>
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = F(<?xml version="1.0" encoding=<%=F(
]]>,
<errors>
<error id="30625"/>
<error id="31172"/>
<error id="31160"/>
<error id="31165"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(682381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682381")>
<Fact()>
Public Sub Bug682381()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= If(1
, 2) %>
End Module
]]>,
<errors>
<error id="31172"/>
<error id="33104"/>
<error id="30198"/>
<error id="31159"/>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(682391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682391")>
<Fact()>
Public Sub Bug682391()
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version <%= e %>
End Module
]]>,
<errors>
<error id="31181"/>
<error id="31172"/>
<error id="30249"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version=1.0 <%= e %>
End Module
]]>,
<errors>
<error id="31181"/>
<error id="31154"/>
<error id="31169"/>
<error id="31173"/>
<error id="31172"/>
<error id="30249"/>
<error id="31160"/>
<error id="31165"/>
</errors>)
End Sub
<WorkItem(682394, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682394")>
<Fact()>
Public Sub Bug682394()
ParseAndVerify(<![CDATA[
Imports <%=:p>
]]>,
<errors>
<error id="31165"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <<%=:p>>
]]>,
<errors>
<error id="31187"/>
<error id="30636"/>
</errors>)
End Sub
<Fact()>
Public Sub IncompleteMultilineLambdaInEmbeddedExpression()
ParseAndVerify(<![CDATA[
Class C
Dim x = <x><%= Sub()
]]>,
<errors>
<error id="30481"/>
<error id="31151"/>
<error id="36673"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<Fact()>
Public Sub FullWidthEmbeddedExpressionTokens()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<", ToFullWidth("<")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<%", ToFullWidth("<%")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("<%=", ToFullWidth("<%=")),
<errors>
<error id="31197"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("%>", ToFullWidth("%") & ">"),
<errors>
<error id="31172"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Nothing %>
End Module
]]>.Value.Replace("%>", ToFullWidth("%>")),
<errors>
<error id="31172"/>
<error id="30035"/>
<error id="30037"/>
<error id="31159"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(684872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684872")>
<Fact()>
Public Sub Bug684872()
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
_
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
_
<x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="32035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x... _
_
<x>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
</x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim y = x...
<%=x>
End Module
]]>,
<errors>
<error id="31165"/>
<error id="31146"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(693901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/693901")>
<Fact()>
Public Sub Bug693901()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, LINE_SEPARATOR),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x/
$>
End Module
]]>.Value.Replace("$"c, PARAGRAPH_SEPARATOR),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="30636"/>
<error id="31169"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$/>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$=""/>
End Module
]]>.Value.Replace("$"c, NEXT_LINE),
<errors>
<error id="31169"/>
</errors>)
End Sub
<WorkItem(716121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716121")>
<Fact()>
Public Sub Bug716121()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, NO_BREAK_SPACE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, IDEOGRAPHIC_SPACE),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
' Test all Unicode space characters other than &H20.
For i = &H21 To &HFFFF
Dim c = ChrW(i)
' Note: SyntaxFacts.IsWhitespace(c) considers &H200B as
' space even though the UnicodeCategory is Format.
If (Char.GetUnicodeCategory(c) = Globalization.UnicodeCategory.SpaceSeparator) OrElse
SyntaxFacts.IsWhitespace(c) Then
ParseAndVerify(<![CDATA[
Module M
Dim x = <x
$!/>
End Module
]]>.Value.Replace("$"c, c),
<errors>
<error id="31169"/>
<error id="30249"/>
</errors>)
End If
Next
End Sub
<WorkItem(697114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697114")>
<Fact()>
Public Sub Bug697114()
' No attributes.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
' One attribute.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
' Two attributes, starting with version.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
</errors>)
' Two attributes, starting with unknown.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
' Two attributes, starting with encoding.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
' Two attributes, starting with standalone.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31149"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
' Three attributes, starting with version.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
</errors>)
' Three attributes, starting with unknown.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" standalone="yes" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31157"/>
<error id="31153"/>
</errors>)
' Three attributes, starting with encoding.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" version="1.0" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml encoding="utf-8" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31153"/>
</errors>)
' Three attributes, starting with standalone.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" version="1.0" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31156"/>
<error id="31157"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a="" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" a="" encoding="utf-8"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
<error id="31157"/>
<error id="31153"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8" version="1.0"?><x/>
End Module
]]>,
<errors>
<error id="31157"/>
<error id="31156"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml standalone="yes" encoding="utf-8" a=""?><x/>
End Module
]]>,
<errors>
<error id="31153"/>
<error id="31157"/>
<error id="31154"/>
</errors>)
' Four attributes.
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml a="" version="1.0" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" a="" encoding="utf-8" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" a="" standalone="yes"?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0" encoding="utf-8" standalone="yes" a=""?><x/>
End Module
]]>,
<errors>
<error id="31154"/>
</errors>)
End Sub
''' <summary>
''' Tests that the REM keyword cannot be neither left nor right part of a qualified XML name.
''' But FULLWIDTH COLON (U+FF1A) should never be parsed as a qualified XML name separator, so REM can follow it.
''' Also, the second colon should never be parsed as a qualified XML name separator.
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub NoRemInXmlNames()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@rem
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "@").WithLocation(4, 22))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@rem:goo
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "@").WithLocation(4, 22))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:rem
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "").WithLocation(4, 27))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:rem$
End Sub
End Module]]>,
Diagnostic(ERRID.ERR_ExpectedXmlName, "").WithLocation(4, 27))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml :rem
End Sub
End Module]]>)
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@xml:goo:rem
End Sub
End Module]]>)
' FULLWIDTH COLON is represented by "~" below
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@goo~rem
End Sub
End Module]]>.Value.Replace("~"c, FULLWIDTH_COLON))
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Dim x = <a/>.@goo~rem$
End Sub
End Module]]>.Value.Replace("~"c, FULLWIDTH_COLON))
End Sub
<WorkItem(969980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969980")>
<WorkItem(123533, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=123533")>
<Fact>
Public Sub UnaliasedXmlImport_Local()
Dim source = "
Imports <xmlns = ""http://xml"">
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll)
Const bug123533IsFixed = False
If bug123533IsFixed Then
compilation.AssertTheseDiagnostics(<expected><![CDATA[
BC50001: Unused import statement.
Imports <xmlns = "http://xml">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>, False)
Else
compilation.AssertTheseDiagnostics(<expected><![CDATA[
BC50001: Unused import statement.
Imports <xmlns = "http://xml">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31187: Namespace declaration must start with 'xmlns'.
Imports <xmlns = "http://xml">
~
BC30636: '>' expected.
Imports <xmlns = "http://xml">
~~~~~
]]></expected>, False)
End If
End Sub
<WorkItem(969980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969980")>
<WorkItem(123533, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=123533")>
<Fact>
Public Sub UnaliasedXmlImport_Project()
Dim import = "<xmlns = ""http://xml"">"
Const bug123533IsFixed = False
If bug123533IsFixed Then
CreateCompilationWithMscorlib40({""}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse(import))).VerifyDiagnostics()
Else
Assert.Throws(Of ArgumentException)(Sub() GlobalImport.Parse(import))
End If
End Sub
<WorkItem(1042696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042696")>
<Fact>
Public Sub ParseXmlTrailingNewLinesBeforeDistinct()
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
<!-- -->
Dim y = x
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <?xml version="1.0"?>
<x/>
<!-- -->
Distinct
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Distinct"))
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
<!-- -->
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <?xml version="1.0"?>
<x/>
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = From y in "" Select <x/>
Distinct
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Distinct"))
ParseAndVerify(<![CDATA[
Module M
Sub F()
If Nothing Is <?xml version="1.0"?>
<x/>
Then
End If
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_Syntax, "Then"))
ParseAndVerify(<![CDATA[
Module M
Sub F()
If Nothing Is <?xml version="1.0"?>
<x/>
<!-- --> Then
End If
End Sub
End Module
]]>)
End Sub
End Class
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/VisualBasic/Portable/Symbols/PointerTypeSymbol.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
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' An error type symbol to represent a pointer type.
''' Pointer types are not supported by VB language, but internally
''' we need to be able to match them in signatures of methods
''' imported from metadata.
''' </summary>
Friend NotInheritable Class PointerTypeSymbol
Inherits ErrorTypeSymbol
Private ReadOnly _pointedAtType As TypeSymbol
Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier)
Public Sub New(pointedAtType As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier))
Debug.Assert(pointedAtType IsNot Nothing)
_pointedAtType = pointedAtType
_customModifiers = customModifiers.NullToEmpty()
End Sub
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ErrorInfo As DiagnosticInfo
Get
Return ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, String.Empty)
End Get
End Property
Public Overrides Function GetHashCode() As Integer
' We don't want to blow the stack if we have a type like T***************...***,
' so we do not recurse until we have a non-pointer.
Dim indirections As Integer = 0
Dim current As PointerTypeSymbol = Me
Dim last As TypeSymbol
Do
indirections += 1
last = current._pointedAtType
current = TryCast(last, PointerTypeSymbol)
Loop While current IsNot Nothing
Return Hash.Combine(last, indirections)
End Function
Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean
If Me Is obj Then
Return True
End If
Dim other = TryCast(obj, PointerTypeSymbol)
Return other IsNot Nothing AndAlso other._pointedAtType.Equals(_pointedAtType, comparison) AndAlso
((comparison And TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) <> 0 OrElse
other._customModifiers.SequenceEqual(_customModifiers))
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
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' An error type symbol to represent a pointer type.
''' Pointer types are not supported by VB language, but internally
''' we need to be able to match them in signatures of methods
''' imported from metadata.
''' </summary>
Friend NotInheritable Class PointerTypeSymbol
Inherits ErrorTypeSymbol
Private ReadOnly _pointedAtType As TypeSymbol
Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier)
Public Sub New(pointedAtType As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier))
Debug.Assert(pointedAtType IsNot Nothing)
_pointedAtType = pointedAtType
_customModifiers = customModifiers.NullToEmpty()
End Sub
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ErrorInfo As DiagnosticInfo
Get
Return ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, String.Empty)
End Get
End Property
Public Overrides Function GetHashCode() As Integer
' We don't want to blow the stack if we have a type like T***************...***,
' so we do not recurse until we have a non-pointer.
Dim indirections As Integer = 0
Dim current As PointerTypeSymbol = Me
Dim last As TypeSymbol
Do
indirections += 1
last = current._pointedAtType
current = TryCast(last, PointerTypeSymbol)
Loop While current IsNot Nothing
Return Hash.Combine(last, indirections)
End Function
Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean
If Me Is obj Then
Return True
End If
Dim other = TryCast(obj, PointerTypeSymbol)
Return other IsNot Nothing AndAlso other._pointedAtType.Equals(_pointedAtType, comparison) AndAlso
((comparison And TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) <> 0 OrElse
other._customModifiers.SequenceEqual(_customModifiers))
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
internal static class Helpers
{
/// <summary>
/// Find an `int MyType.Count` or `int MyType.Length` property.
/// </summary>
public static IPropertySymbol TryGetLengthOrCountProperty(ITypeSymbol namedType)
=> TryGetNoArgInt32Property(namedType, nameof(string.Length)) ??
TryGetNoArgInt32Property(namedType, nameof(ICollection.Count));
/// <summary>
/// Tried to find a public, non-static, int-returning property in the given type with the
/// specified <paramref name="name"/>.
/// </summary>
public static IPropertySymbol TryGetNoArgInt32Property(ITypeSymbol type, string name)
=> type.GetMembers(name)
.OfType<IPropertySymbol>()
.Where(p => IsPublicInstance(p) &&
p.Type.SpecialType == SpecialType.System_Int32)
.FirstOrDefault();
public static bool IsPublicInstance(ISymbol symbol)
=> !symbol.IsStatic && symbol.DeclaredAccessibility == Accessibility.Public;
/// <summary>
/// Checks if this <paramref name="operation"/> is `expr.Length` where `expr` is equivalent
/// to the <paramref name="instance"/> we were originally invoking an accessor/method off
/// of.
/// </summary>
public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOperation instance, IOperation operation)
=> operation is IPropertyReferenceOperation propertyRef &&
propertyRef.Instance != null &&
lengthLikeProperty.Equals(propertyRef.Property) &&
CSharpSyntaxFacts.Instance.AreEquivalent(instance.Syntax, propertyRef.Instance.Syntax);
/// <summary>
/// Checks if <paramref name="operation"/> is a binary subtraction operator. If so, it
/// will be returned through <paramref name="subtraction"/>.
/// </summary>
public static bool IsSubtraction(IOperation operation, out IBinaryOperation subtraction)
{
if (operation is IBinaryOperation binaryOperation &&
binaryOperation.OperatorKind == BinaryOperatorKind.Subtract)
{
subtraction = binaryOperation;
return true;
}
subtraction = null;
return false;
}
/// <summary>
/// Look for methods like "SomeType MyType.Get(int)". Also matches against the 'getter'
/// of an indexer like 'SomeType MyType.this[int]`
/// </summary>
public static bool IsIntIndexingMethod(IMethodSymbol method)
=> method != null &&
(method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.Ordinary) &&
IsPublicInstance(method) &&
method.Parameters.Length == 1 &&
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
method.OriginalDefinition.Parameters[0].Type.SpecialType == SpecialType.System_Int32;
/// <summary>
/// Look for methods like "SomeType MyType.Slice(int start, int length)". Note that the
/// names of the parameters are checked to ensure they are appropriate slice-like. These
/// names were picked by examining the patterns in the BCL for slicing members.
/// </summary>
public static bool IsTwoArgumentSliceLikeMethod(IMethodSymbol method)
{
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
return method != null &&
IsPublicInstance(method) &&
method.Parameters.Length == 2 &&
IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]) &&
IsSliceSecondParameter(method.OriginalDefinition.Parameters[1]);
}
/// <summary>
/// Look for methods like "SomeType MyType.Slice(int start)". Note that the
/// name of the parameter is checked to ensure it is appropriate slice-like.
/// This name was picked by examining the patterns in the BCL for slicing members.
/// </summary>
public static bool IsOneArgumentSliceLikeMethod(IMethodSymbol method)
{
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
return method != null &&
IsPublicInstance(method) &&
method.Parameters.Length == 1 &&
IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]);
}
private static bool IsSliceFirstParameter(IParameterSymbol parameter)
=> parameter.Type.SpecialType == SpecialType.System_Int32 &&
(parameter.Name == "start" || parameter.Name == "startIndex");
private static bool IsSliceSecondParameter(IParameterSymbol parameter)
=> parameter.Type.SpecialType == SpecialType.System_Int32 &&
(parameter.Name == "count" || parameter.Name == "length");
/// <summary>
/// Finds a public, non-static indexer in the given type. The indexer has to accept the
/// provided <paramref name="parameterType"/> and must return the provided <paramref
/// name="returnType"/>.
/// </summary>
public static IPropertySymbol GetIndexer(ITypeSymbol type, ITypeSymbol parameterType, ITypeSymbol returnType)
=> type.GetMembers(WellKnownMemberNames.Indexer)
.OfType<IPropertySymbol>()
.Where(p => p.IsIndexer &&
IsPublicInstance(p) &&
returnType.Equals(p.Type) &&
p.Parameters.Length == 1 &&
p.Parameters[0].Type.Equals(parameterType))
.FirstOrDefault();
/// <summary>
/// Finds a public, non-static overload of <paramref name="method"/> in the containing type.
/// The overload must have the same return type as <paramref name="method"/>. It must only
/// have a single parameter, with the provided <paramref name="parameterType"/>.
/// </summary>
public static IMethodSymbol GetOverload(IMethodSymbol method, ITypeSymbol parameterType)
=> method.MethodKind != MethodKind.Ordinary
? null
: method.ContainingType.GetMembers(method.Name)
.OfType<IMethodSymbol>()
.Where(m => IsPublicInstance(m) &&
m.Parameters.Length == 1 &&
m.Parameters[0].Type.Equals(parameterType) &&
m.ReturnType.Equals(method.ReturnType))
.FirstOrDefault();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
internal static class Helpers
{
/// <summary>
/// Find an `int MyType.Count` or `int MyType.Length` property.
/// </summary>
public static IPropertySymbol TryGetLengthOrCountProperty(ITypeSymbol namedType)
=> TryGetNoArgInt32Property(namedType, nameof(string.Length)) ??
TryGetNoArgInt32Property(namedType, nameof(ICollection.Count));
/// <summary>
/// Tried to find a public, non-static, int-returning property in the given type with the
/// specified <paramref name="name"/>.
/// </summary>
public static IPropertySymbol TryGetNoArgInt32Property(ITypeSymbol type, string name)
=> type.GetMembers(name)
.OfType<IPropertySymbol>()
.Where(p => IsPublicInstance(p) &&
p.Type.SpecialType == SpecialType.System_Int32)
.FirstOrDefault();
public static bool IsPublicInstance(ISymbol symbol)
=> !symbol.IsStatic && symbol.DeclaredAccessibility == Accessibility.Public;
/// <summary>
/// Checks if this <paramref name="operation"/> is `expr.Length` where `expr` is equivalent
/// to the <paramref name="instance"/> we were originally invoking an accessor/method off
/// of.
/// </summary>
public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOperation instance, IOperation operation)
=> operation is IPropertyReferenceOperation propertyRef &&
propertyRef.Instance != null &&
lengthLikeProperty.Equals(propertyRef.Property) &&
CSharpSyntaxFacts.Instance.AreEquivalent(instance.Syntax, propertyRef.Instance.Syntax);
/// <summary>
/// Checks if <paramref name="operation"/> is a binary subtraction operator. If so, it
/// will be returned through <paramref name="subtraction"/>.
/// </summary>
public static bool IsSubtraction(IOperation operation, out IBinaryOperation subtraction)
{
if (operation is IBinaryOperation binaryOperation &&
binaryOperation.OperatorKind == BinaryOperatorKind.Subtract)
{
subtraction = binaryOperation;
return true;
}
subtraction = null;
return false;
}
/// <summary>
/// Look for methods like "SomeType MyType.Get(int)". Also matches against the 'getter'
/// of an indexer like 'SomeType MyType.this[int]`
/// </summary>
public static bool IsIntIndexingMethod(IMethodSymbol method)
=> method != null &&
(method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.Ordinary) &&
IsPublicInstance(method) &&
method.Parameters.Length == 1 &&
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
method.OriginalDefinition.Parameters[0].Type.SpecialType == SpecialType.System_Int32;
/// <summary>
/// Look for methods like "SomeType MyType.Slice(int start, int length)". Note that the
/// names of the parameters are checked to ensure they are appropriate slice-like. These
/// names were picked by examining the patterns in the BCL for slicing members.
/// </summary>
public static bool IsTwoArgumentSliceLikeMethod(IMethodSymbol method)
{
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
return method != null &&
IsPublicInstance(method) &&
method.Parameters.Length == 2 &&
IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]) &&
IsSliceSecondParameter(method.OriginalDefinition.Parameters[1]);
}
/// <summary>
/// Look for methods like "SomeType MyType.Slice(int start)". Note that the
/// name of the parameter is checked to ensure it is appropriate slice-like.
/// This name was picked by examining the patterns in the BCL for slicing members.
/// </summary>
public static bool IsOneArgumentSliceLikeMethod(IMethodSymbol method)
{
// From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation
//
// When looking for the pattern members, we look for original definitions, not
// constructed members
return method != null &&
IsPublicInstance(method) &&
method.Parameters.Length == 1 &&
IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]);
}
private static bool IsSliceFirstParameter(IParameterSymbol parameter)
=> parameter.Type.SpecialType == SpecialType.System_Int32 &&
(parameter.Name == "start" || parameter.Name == "startIndex");
private static bool IsSliceSecondParameter(IParameterSymbol parameter)
=> parameter.Type.SpecialType == SpecialType.System_Int32 &&
(parameter.Name == "count" || parameter.Name == "length");
/// <summary>
/// Finds a public, non-static indexer in the given type. The indexer has to accept the
/// provided <paramref name="parameterType"/> and must return the provided <paramref
/// name="returnType"/>.
/// </summary>
public static IPropertySymbol GetIndexer(ITypeSymbol type, ITypeSymbol parameterType, ITypeSymbol returnType)
=> type.GetMembers(WellKnownMemberNames.Indexer)
.OfType<IPropertySymbol>()
.Where(p => p.IsIndexer &&
IsPublicInstance(p) &&
returnType.Equals(p.Type) &&
p.Parameters.Length == 1 &&
p.Parameters[0].Type.Equals(parameterType))
.FirstOrDefault();
/// <summary>
/// Finds a public, non-static overload of <paramref name="method"/> in the containing type.
/// The overload must have the same return type as <paramref name="method"/>. It must only
/// have a single parameter, with the provided <paramref name="parameterType"/>.
/// </summary>
public static IMethodSymbol GetOverload(IMethodSymbol method, ITypeSymbol parameterType)
=> method.MethodKind != MethodKind.Ordinary
? null
: method.ContainingType.GetMembers(method.Name)
.OfType<IMethodSymbol>()
.Where(m => IsPublicInstance(m) &&
m.Parameters.Length == 1 &&
m.Parameters[0].Type.Equals(parameterType) &&
m.ReturnType.Equals(method.ReturnType))
.FirstOrDefault();
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodeFunctionTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeFunctionTests
Inherits AbstractCodeFunctionTests
#Region "FullName tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFullName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestFullName(code, "C.Goo")
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestName(code, "Goo")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeFunctionTests
Inherits AbstractCodeFunctionTests
#Region "FullName tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFullName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestFullName(code, "C.Goo")
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestName(code, "Goo")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.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.WindowsDesktop">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Roslyn.Hosting.Diagnostics</RootNamespace>
<TargetFramework>net472</TargetFramework>
<UseWpf>true</UseWpf>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" />
<InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" />
</ItemGroup>
</Project>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Roslyn.Hosting.Diagnostics</RootNamespace>
<TargetFramework>net472</TargetFramework>
<UseWpf>true</UseWpf>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" />
<InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" />
</ItemGroup>
</Project>
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/DestructorDeclarationStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
public class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<DestructorDeclarationSyntax>
{
protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task NoCommentsOrAttributes()
{
const string code = @"
class Goo
{
$$~Goo();
}";
await VerifyNoBlockSpansAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task WithAttributes()
{
const string code = @"
class Goo
{
{|hint:{|textspan:[Bar]
|}$$~Goo();|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task WithCommentsAndAttributes()
{
const string code = @"
class Goo
{
{|hint:{|textspan:// Summary:
// This is a summary.
[Bar]
|}$$~Goo();|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
public class DestructorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<DestructorDeclarationSyntax>
{
protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
internal override AbstractSyntaxStructureProvider CreateProvider() => new DestructorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task NoCommentsOrAttributes()
{
const string code = @"
class Goo
{
$$~Goo();
}";
await VerifyNoBlockSpansAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task WithAttributes()
{
const string code = @"
class Goo
{
{|hint:{|textspan:[Bar]
|}$$~Goo();|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task WithCommentsAndAttributes()
{
const string code = @"
class Goo
{
{|hint:{|textspan:// Summary:
// This is a summary.
[Bar]
|}$$~Goo();|}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Analyzers/Core/CodeFixes/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseObjectInitializer
{
internal abstract class AbstractUseObjectInitializerCodeFixProvider<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TAssignmentStatementSyntax,
TVariableDeclaratorSyntax>
: SyntaxEditorBasedCodeFixProvider
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TAssignmentStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
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)
{
// Fix-All for this feature is somewhat complicated. As Object-Initializers
// could be arbitrarily nested, we have to make sure that any edits we make
// to one Object-Initializer are seen by any higher ones. In order to do this
// we actually process each object-creation-node, one at a time, rewriting
// the tree for each node. In order to do this effectively, we use the '.TrackNodes'
// feature to keep track of all the object creation nodes as we make edits to
// the tree. If we didn't do this, then we wouldn't be able to find the
// second object-creation-node after we make the edit for the first one.
var workspace = document.Project.Solution.Workspace;
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var originalRoot = editor.OriginalRoot;
var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>();
foreach (var diagnostic in diagnostics)
{
var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode(
diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
originalObjectCreationNodes.Push(objectCreation);
}
// We're going to be continually editing this tree. Track all the nodes we
// care about so we can find them across each edit.
document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes));
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
while (originalObjectCreationNodes.Count > 0)
{
var originalObjectCreation = originalObjectCreationNodes.Pop();
var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single();
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
semanticModel, syntaxFacts, objectCreation, cancellationToken);
if (matches == null || matches.Value.Length == 0)
{
continue;
}
var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>();
var newStatement = GetNewStatement(statement, objectCreation, matches.Value)
.WithAdditionalAnnotations(Formatter.Annotation);
var subEditor = new SyntaxEditor(currentRoot, workspace);
subEditor.ReplaceNode(statement, newStatement);
foreach (var match in matches)
{
subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
document = document.WithSyntaxRoot(subEditor.GetChangedRoot());
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
editor.ReplaceNode(editor.OriginalRoot, currentRoot);
}
protected abstract TStatementSyntax GetNewStatement(
TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches);
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseObjectInitializer
{
internal abstract class AbstractUseObjectInitializerCodeFixProvider<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TAssignmentStatementSyntax,
TVariableDeclaratorSyntax>
: SyntaxEditorBasedCodeFixProvider
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TAssignmentStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
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)
{
// Fix-All for this feature is somewhat complicated. As Object-Initializers
// could be arbitrarily nested, we have to make sure that any edits we make
// to one Object-Initializer are seen by any higher ones. In order to do this
// we actually process each object-creation-node, one at a time, rewriting
// the tree for each node. In order to do this effectively, we use the '.TrackNodes'
// feature to keep track of all the object creation nodes as we make edits to
// the tree. If we didn't do this, then we wouldn't be able to find the
// second object-creation-node after we make the edit for the first one.
var workspace = document.Project.Solution.Workspace;
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var originalRoot = editor.OriginalRoot;
var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>();
foreach (var diagnostic in diagnostics)
{
var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode(
diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
originalObjectCreationNodes.Push(objectCreation);
}
// We're going to be continually editing this tree. Track all the nodes we
// care about so we can find them across each edit.
document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes));
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
while (originalObjectCreationNodes.Count > 0)
{
var originalObjectCreation = originalObjectCreationNodes.Pop();
var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single();
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
semanticModel, syntaxFacts, objectCreation, cancellationToken);
if (matches == null || matches.Value.Length == 0)
{
continue;
}
var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>();
var newStatement = GetNewStatement(statement, objectCreation, matches.Value)
.WithAdditionalAnnotations(Formatter.Annotation);
var subEditor = new SyntaxEditor(currentRoot, workspace);
subEditor.ReplaceNode(statement, newStatement);
foreach (var match in matches)
{
subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
document = document.WithSyntaxRoot(subEditor.GetChangedRoot());
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
editor.ReplaceNode(editor.OriginalRoot, currentRoot);
}
protected abstract TStatementSyntax GetNewStatement(
TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches);
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified))
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/VisualStudio/Core/Def/Implementation/PickMembers/PickMembersDialogViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged
{
private readonly List<MemberSymbolViewModel> _allMembers;
public List<MemberSymbolViewModel> MemberContainers { get; set; }
public List<OptionViewModel> Options { get; set; }
/// <summary>
/// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen.
/// </summary>
public bool SelectedAll { get; set; }
internal PickMembersDialogViewModel(
IGlyphService glyphService,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
_allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList();
MemberContainers = _allMembers;
Options = options.Select(o => new OptionViewModel(o)).ToList();
if (selectAll)
{
SelectAll();
}
else
{
DeselectAll();
}
}
internal void Filter(string searchText)
{
searchText = searchText.Trim();
MemberContainers = searchText.Length == 0
? _allMembers
: _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
NotifyPropertyChanged(nameof(MemberContainers));
}
internal void DeselectAll()
{
SelectedAll = false;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = false;
}
internal void SelectAll()
{
SelectedAll = true;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = true;
}
private int? _selectedIndex;
public int? SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var newSelectedIndex = value == -1 ? null : value;
if (newSelectedIndex == _selectedIndex)
{
return;
}
_selectedIndex = newSelectedIndex;
NotifyPropertyChanged(nameof(CanMoveUp));
NotifyPropertyChanged(nameof(MoveUpAutomationText));
NotifyPropertyChanged(nameof(CanMoveDown));
NotifyPropertyChanged(nameof(MoveDownAutomationText));
}
}
public string MoveUpAutomationText
{
get
{
if (!CanMoveUp)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText);
}
}
public string MoveDownAutomationText
{
get
{
if (!CanMoveDown)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText);
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveUp
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index > 0;
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveDown
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index < MemberContainers.Count - 1;
}
}
internal void MoveUp()
{
Contract.ThrowIfFalse(CanMoveUp);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: -1);
}
internal void MoveDown()
{
Contract.ThrowIfFalse(CanMoveDown);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: 1);
}
private void Move(List<MemberSymbolViewModel> list, int index, int delta)
{
var param = list[index];
list.RemoveAt(index);
list.Insert(index + delta, param);
SelectedIndex += delta;
}
internal class MemberSymbolViewModel : SymbolViewModel<ISymbol>
{
public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService)
{
}
}
internal class OptionViewModel : AbstractNotifyPropertyChanged
{
public PickMembersOption Option { get; }
public string Title { get; }
public OptionViewModel(PickMembersOption option)
{
Option = option;
Title = option.Title;
IsChecked = option.Value;
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
Option.Value = value;
SetProperty(ref _isChecked, value);
}
}
public string MemberAutomationText => Option.Title;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged
{
private readonly List<MemberSymbolViewModel> _allMembers;
public List<MemberSymbolViewModel> MemberContainers { get; set; }
public List<OptionViewModel> Options { get; set; }
/// <summary>
/// <see langword="true"/> if 'Select All' was chosen. <see langword="false"/> if 'Deselect All' was chosen.
/// </summary>
public bool SelectedAll { get; set; }
internal PickMembersDialogViewModel(
IGlyphService glyphService,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
_allMembers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList();
MemberContainers = _allMembers;
Options = options.Select(o => new OptionViewModel(o)).ToList();
if (selectAll)
{
SelectAll();
}
else
{
DeselectAll();
}
}
internal void Filter(string searchText)
{
searchText = searchText.Trim();
MemberContainers = searchText.Length == 0
? _allMembers
: _allMembers.Where(m => m.SymbolAutomationText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
NotifyPropertyChanged(nameof(MemberContainers));
}
internal void DeselectAll()
{
SelectedAll = false;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = false;
}
internal void SelectAll()
{
SelectedAll = true;
foreach (var memberContainer in MemberContainers)
memberContainer.IsChecked = true;
}
private int? _selectedIndex;
public int? SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var newSelectedIndex = value == -1 ? null : value;
if (newSelectedIndex == _selectedIndex)
{
return;
}
_selectedIndex = newSelectedIndex;
NotifyPropertyChanged(nameof(CanMoveUp));
NotifyPropertyChanged(nameof(MoveUpAutomationText));
NotifyPropertyChanged(nameof(CanMoveDown));
NotifyPropertyChanged(nameof(MoveDownAutomationText));
}
}
public string MoveUpAutomationText
{
get
{
if (!CanMoveUp)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value - 1].SymbolAutomationText);
}
}
public string MoveDownAutomationText
{
get
{
if (!CanMoveDown)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].SymbolAutomationText, MemberContainers[SelectedIndex.Value + 1].SymbolAutomationText);
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveUp
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index > 0;
}
}
[MemberNotNullWhen(true, nameof(SelectedIndex))]
public bool CanMoveDown
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index < MemberContainers.Count - 1;
}
}
internal void MoveUp()
{
Contract.ThrowIfFalse(CanMoveUp);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: -1);
}
internal void MoveDown()
{
Contract.ThrowIfFalse(CanMoveDown);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: 1);
}
private void Move(List<MemberSymbolViewModel> list, int index, int delta)
{
var param = list[index];
list.RemoveAt(index);
list.Insert(index + delta, param);
SelectedIndex += delta;
}
internal class MemberSymbolViewModel : SymbolViewModel<ISymbol>
{
public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService)
{
}
}
internal class OptionViewModel : AbstractNotifyPropertyChanged
{
public PickMembersOption Option { get; }
public string Title { get; }
public OptionViewModel(PickMembersOption option)
{
Option = option;
Title = option.Title;
IsChecked = option.Value;
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
Option.Value = value;
SetProperty(ref _isChecked, value);
}
}
public string MemberAutomationText => Option.Title;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/VisualBasic/Portable/Structure/Providers/DocumentationCommentStructureProvider.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class DocumentationCommentStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of DocumentationCommentTriviaSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
documentationComment As DocumentationCommentTriviaSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
Dim firstCommentToken = documentationComment.ChildNodesAndTokens().FirstOrNull()
Dim lastCommentToken = documentationComment.ChildNodesAndTokens().LastOrNull()
If firstCommentToken Is Nothing Then
Return
End If
' TODO: Need to redo this when DocumentationCommentTrivia.SpanStart points to the start of the exterior trivia.
Dim startPos = firstCommentToken.Value.FullSpan.Start
' The trailing newline is included in DocumentationCommentTrivia, so we need to strip it.
Dim endPos = lastCommentToken.Value.SpanStart + lastCommentToken.Value.ToString().TrimEnd().Length
Dim fullSpan = TextSpan.FromBounds(startPos, endPos)
Dim maxBannerLength = optionProvider.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.VisualBasic)
Dim bannerText = VisualBasicSyntaxFacts.Instance.GetBannerText(
documentationComment, maxBannerLength, cancellationToken)
spans.AddIfNotNull(CreateBlockSpan(
fullSpan, fullSpan, bannerText,
autoCollapse:=True, type:=BlockTypes.Comment,
isCollapsible:=True, isDefaultCollapsed:=False))
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class DocumentationCommentStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of DocumentationCommentTriviaSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
documentationComment As DocumentationCommentTriviaSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
Dim firstCommentToken = documentationComment.ChildNodesAndTokens().FirstOrNull()
Dim lastCommentToken = documentationComment.ChildNodesAndTokens().LastOrNull()
If firstCommentToken Is Nothing Then
Return
End If
' TODO: Need to redo this when DocumentationCommentTrivia.SpanStart points to the start of the exterior trivia.
Dim startPos = firstCommentToken.Value.FullSpan.Start
' The trailing newline is included in DocumentationCommentTrivia, so we need to strip it.
Dim endPos = lastCommentToken.Value.SpanStart + lastCommentToken.Value.ToString().TrimEnd().Length
Dim fullSpan = TextSpan.FromBounds(startPos, endPos)
Dim maxBannerLength = optionProvider.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.VisualBasic)
Dim bannerText = VisualBasicSyntaxFacts.Instance.GetBannerText(
documentationComment, maxBannerLength, cancellationToken)
spans.AddIfNotNull(CreateBlockSpan(
fullSpan, fullSpan, bannerText,
autoCollapse:=True, type:=BlockTypes.Comment,
isCollapsible:=True, isDefaultCollapsed:=False))
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Features/Core/Portable/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor
{
internal static class GenerateConstructorHelpers
{
public static bool CanDelegateTo<TExpressionSyntax>(
SemanticDocument document,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<TExpressionSyntax?> expressions,
IMethodSymbol constructor)
where TExpressionSyntax : SyntaxNode
{
// Look for constructors in this specified type that are:
// 1. Accessible. We obviously need our constructor to be able to call that other constructor.
// 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor,
// then we don't want it calling back into us.
// 3. Are compatible with the parameters we're generating for this constructor. Compatible means there
// exists an implicit conversion from the new constructor's parameter types to the existing
// constructor's parameter types.
var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var compilation = semanticModel.Compilation;
return constructor.Parameters.Length == parameters.Length &&
constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) &&
IsSymbolAccessible(compilation, constructor) &&
IsCompatible(semanticFacts, semanticModel, constructor, expressions);
}
private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol)
{
if (symbol == null)
return false;
if (symbol is IPropertySymbol { SetMethod: { } setMethod } property &&
!IsSymbolAccessible(compilation, setMethod))
{
return false;
}
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
return compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly);
default:
return false;
}
}
private static bool IsCompatible<TExpressionSyntax>(
ISemanticFactsService semanticFacts,
SemanticModel semanticModel,
IMethodSymbol constructor,
ImmutableArray<TExpressionSyntax?> expressions)
where TExpressionSyntax : SyntaxNode
{
Debug.Assert(constructor.Parameters.Length == expressions.Length);
// Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from
// another project with a different language.
var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol;
if (constructorInCompilation == null)
{
// If the constructor can't be mapped into our invocation project, we'll just bail.
// Note the logic in this method doesn't handle a complicated case where:
//
// 1. Project A has some public type.
// 2. Project B references A, and has one constructor that uses the public type from A.
// 3. Project C, which references B but not A, has an invocation of B's constructor passing some
// parameters.
//
// The algorithm of this class tries to map the constructor in B (that we might delegate to) into
// C, but that constructor might not be mappable if the public type from A is not available.
// However, theoretically the public type from A could have a user-defined conversion.
// The alternative approach might be to map the type of the parameters back into B, and then
// classify the conversions in Project B, but that'll run into other issues if the experssions
// don't have a natural type (like default). We choose to ignore all complicated cases here.
return false;
}
for (var i = 0; i < constructorInCompilation.Parameters.Length; i++)
{
var constructorParameter = constructorInCompilation.Parameters[i];
if (constructorParameter == null)
return false;
// In VB the argument may not have been specified at all if the parameter is optional
if (expressions[i] is null && constructorParameter.IsOptional)
continue;
var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type);
if (!conversion.IsIdentity && !conversion.IsImplicit)
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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor
{
internal static class GenerateConstructorHelpers
{
public static bool CanDelegateTo<TExpressionSyntax>(
SemanticDocument document,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<TExpressionSyntax?> expressions,
IMethodSymbol constructor)
where TExpressionSyntax : SyntaxNode
{
// Look for constructors in this specified type that are:
// 1. Accessible. We obviously need our constructor to be able to call that other constructor.
// 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor,
// then we don't want it calling back into us.
// 3. Are compatible with the parameters we're generating for this constructor. Compatible means there
// exists an implicit conversion from the new constructor's parameter types to the existing
// constructor's parameter types.
var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var compilation = semanticModel.Compilation;
return constructor.Parameters.Length == parameters.Length &&
constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) &&
IsSymbolAccessible(compilation, constructor) &&
IsCompatible(semanticFacts, semanticModel, constructor, expressions);
}
private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol)
{
if (symbol == null)
return false;
if (symbol is IPropertySymbol { SetMethod: { } setMethod } property &&
!IsSymbolAccessible(compilation, setMethod))
{
return false;
}
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
return compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly);
default:
return false;
}
}
private static bool IsCompatible<TExpressionSyntax>(
ISemanticFactsService semanticFacts,
SemanticModel semanticModel,
IMethodSymbol constructor,
ImmutableArray<TExpressionSyntax?> expressions)
where TExpressionSyntax : SyntaxNode
{
Debug.Assert(constructor.Parameters.Length == expressions.Length);
// Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from
// another project with a different language.
var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol;
if (constructorInCompilation == null)
{
// If the constructor can't be mapped into our invocation project, we'll just bail.
// Note the logic in this method doesn't handle a complicated case where:
//
// 1. Project A has some public type.
// 2. Project B references A, and has one constructor that uses the public type from A.
// 3. Project C, which references B but not A, has an invocation of B's constructor passing some
// parameters.
//
// The algorithm of this class tries to map the constructor in B (that we might delegate to) into
// C, but that constructor might not be mappable if the public type from A is not available.
// However, theoretically the public type from A could have a user-defined conversion.
// The alternative approach might be to map the type of the parameters back into B, and then
// classify the conversions in Project B, but that'll run into other issues if the experssions
// don't have a natural type (like default). We choose to ignore all complicated cases here.
return false;
}
for (var i = 0; i < constructorInCompilation.Parameters.Length; i++)
{
var constructorParameter = constructorInCompilation.Parameters[i];
if (constructorParameter == null)
return false;
// In VB the argument may not have been specified at all if the parameter is optional
if (expressions[i] is null && constructorParameter.IsOptional)
continue;
var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type);
if (!conversion.IsIdentity && !conversion.IsImplicit)
return false;
}
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/IDocumentationCommentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal interface IDocumentationCommentService
{
string GetBannerText(SyntaxNode documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal interface IDocumentationCommentService
{
string GetBannerText(SyntaxNode documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 56,258 | Null annotate preview generation | jasonmalinowski | "2021-09-08T20:32:54Z" | "2021-09-09T02:35:33Z" | 897c0d1a277876f02c5d902731b95f2b7cb8e587 | 3c68fe73e5db8b425152f15019cd80759cedf88f | Null annotate preview generation. | ./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestLib11.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L [L ! # @ @ @ " O @ ` H .text $ `.rsrc @ @ @.reloc `
@ B # H d h
*(
*(
* BSJB v4.0.30319 l #~ ` #Strings #US #GUID , < |