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> &lt; </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="&amp; &lt; &gt; &apos; &quot;"></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>&lt;</> End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Public Module Module1 Public Sub Main() Dim buildx = <xml>&lt;&gt;</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="&#x30"> Module M Private F = <x>&lt;&#x5a</x> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31178: Expected closing ';' for XML entity. Imports <xmlns:p="&#x30"> ~~~~~ BC31178: Expected closing ';' for XML entity. Private F = <x>&lt;&#x5a</x> ~~~~~ ]]></errors>) End Sub <WorkItem(882874, "DevDiv/Personal")> <Fact> Public Sub BC31178ERR_ExpectedSColon_ParseXmlEntity() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() dim z = <goo attr1="&amp"></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&amp;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>&#1234; &#60; &#70;</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 = &lt;! [CDATA[]]&gt; '&lt;/&gt; '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="&#120; &#60; &#65;"></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 &lt;![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> &lt; </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="&amp; &lt; &gt; &apos; &quot;"></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>&lt;</> End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Public Module Module1 Public Sub Main() Dim buildx = <xml>&lt;&gt;</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="&#x30"> Module M Private F = <x>&lt;&#x5a</x> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31178: Expected closing ';' for XML entity. Imports <xmlns:p="&#x30"> ~~~~~ BC31178: Expected closing ';' for XML entity. Private F = <x>&lt;&#x5a</x> ~~~~~ ]]></errors>) End Sub <WorkItem(882874, "DevDiv/Personal")> <Fact> Public Sub BC31178ERR_ExpectedSColon_ParseXmlEntity() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() dim z = <goo attr1="&amp"></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&amp;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>&#1234; &#60; &#70;</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 = &lt;! [CDATA[]]&gt; '&lt;/&gt; '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="&#120; &#60; &#65;"></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 &lt;![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. $PEL[L! # @@ @"O@`  H.text$  `.rsrc@@@.reloc ` @B#Hd h *( *( *BSJB v4.0.30319l#~`#Strings#US#GUID,<#BlobG %3 6/hHH P = S B [ B BB B . .&<Module>ErrTestLib11.dllANSN1.N2mscorlibSystemObjectTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib11 ZBZB|z\V4  TWrapNonExceptionThrows"# #_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib11.dll(LegalCopyright LOriginalFilenameErrTestLib11.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
MZ@ !L!This program cannot be run in DOS mode. $PEL[L! # @@ @"O@`  H.text$  `.rsrc@@@.reloc ` @B#Hd h *( *( *BSJB v4.0.30319l#~`#Strings#US#GUID,<#BlobG %3 6/hHH P = S B [ B BB B . .&<Module>ErrTestLib11.dllANSN1.N2mscorlibSystemObjectTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib11 ZBZB|z\V4  TWrapNonExceptionThrows"# #_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib11.dll(LegalCopyright LOriginalFilenameErrTestLib11.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
-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/AbstractSignatureHelpCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { internal abstract class AbstractSignatureHelpCommandHandler : ForegroundThreadAffinitizedObject { private readonly SignatureHelpControllerProvider _controllerProvider; public AbstractSignatureHelpCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext) { _controllerProvider = controllerProvider; } protected bool TryGetController(EditorCommandArgs args, out Controller controller) { AssertIsForeground(); // If args is `InvokeSignatureHelpCommandArgs` then sig help was explicitly invoked by the user and should // be shown whether or not the option is set. if (!(args is InvokeSignatureHelpCommandArgs) && !args.SubjectBuffer.GetFeatureOnOffOption(SignatureHelpOptions.ShowSignatureHelp)) { controller = null; return false; } controller = _controllerProvider.GetController(args.TextView, args.SubjectBuffer); return controller is not 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 Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { internal abstract class AbstractSignatureHelpCommandHandler : ForegroundThreadAffinitizedObject { private readonly SignatureHelpControllerProvider _controllerProvider; public AbstractSignatureHelpCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider controllerProvider) : base(threadingContext) { _controllerProvider = controllerProvider; } protected bool TryGetController(EditorCommandArgs args, out Controller controller) { AssertIsForeground(); // If args is `InvokeSignatureHelpCommandArgs` then sig help was explicitly invoked by the user and should // be shown whether or not the option is set. if (!(args is InvokeSignatureHelpCommandArgs) && !args.SubjectBuffer.GetFeatureOnOffOption(SignatureHelpOptions.ShowSignatureHelp)) { controller = null; return false; } controller = _controllerProvider.GetController(args.TextView, args.SubjectBuffer); return controller is not 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/EditorFeatures/VisualBasicTest/Recommendations/Declarations/GetSetKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class GetSetKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Private |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Protected |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Friend |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Protected Friend |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Friend Protected |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyTest() VerifyRecommendationsContain(<ClassDeclaration>Property ReadOnly Goo As Integer |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property ReadOnly Goo As Integer Private |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Protected |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Friend |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Protected Friend |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Friend Protected |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Private |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Protected |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Friend |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Protected Friend |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Friend Protected |</ClassDeclaration>, "Set") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class GetSetKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Private |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Protected |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Friend |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Protected Friend |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAndSetAfterAutoPropAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property Goo As Integer Friend Protected |</ClassDeclaration>, "Get", "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyTest() VerifyRecommendationsContain(<ClassDeclaration>Property ReadOnly Goo As Integer |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>Property ReadOnly Goo As Integer Private |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Protected |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Friend |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Protected Friend |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub GetAfterReadOnlyPropertyAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly Property Goo As Integer Friend Protected |</ClassDeclaration>, "Get") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndPrivateAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Private |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Protected |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Friend |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndProtectedFriendAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Protected Friend |</ClassDeclaration>, "Set") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SetAfterWriteOnlyPropertyAndFriendProtectedAccessorTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly Property Goo As Integer Friend Protected |</ClassDeclaration>, "Set") 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/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.MatchFolderAndNamespace { internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) { context.RegisterCodeFix( new MyCodeAction(AnalyzersResources.Change_namespace_to_match_folder_structure, cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, cancellationToken)), context.Diagnostics); } return Task.CompletedTask; } private static async Task<Solution> FixAllInDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // All the target namespaces should be the same for a given document Debug.Assert(diagnostics.Select(diagnostic => diagnostic.Properties[MatchFolderAndNamespaceConstants.TargetNamespace]).Distinct().Count() == 1); var targetNamespace = diagnostics.First().Properties[MatchFolderAndNamespaceConstants.TargetNamespace]; RoslynDebug.AssertNotNull(targetNamespace); // Use the Renamer.RenameDocumentAsync API to sync namespaces in the document. This allows // us to keep in line with the sync methodology that we have as a public API and not have // to rewrite or move the complex logic. RenameDocumentAsync is designed to behave the same // as the intent of this analyzer/codefix pair. var targetFolders = PathMetadataUtilities.BuildFoldersFromNamespace(targetNamespace, document.Project.DefaultNamespace); var documentWithInvalidFolders = document.WithFolders(document.Folders.Concat("Force-Namespace-Change")); var renameActionSet = await Renamer.RenameDocumentAsync( documentWithInvalidFolders, documentWithInvalidFolders.Name, newDocumentFolders: targetFolders, cancellationToken: cancellationToken).ConfigureAwait(false); var newSolution = await renameActionSet.UpdateSolutionAsync(documentWithInvalidFolders.Project.Solution, cancellationToken).ConfigureAwait(false); Debug.Assert(newSolution != document.Project.Solution); return newSolution; } public override FixAllProvider? GetFixAllProvider() => CustomFixAllProvider.Instance; private sealed class MyCodeAction : CustomCodeActions.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, 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.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.MatchFolderAndNamespace { internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) { context.RegisterCodeFix( new MyCodeAction(AnalyzersResources.Change_namespace_to_match_folder_structure, cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, cancellationToken)), context.Diagnostics); } return Task.CompletedTask; } private static async Task<Solution> FixAllInDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // All the target namespaces should be the same for a given document Debug.Assert(diagnostics.Select(diagnostic => diagnostic.Properties[MatchFolderAndNamespaceConstants.TargetNamespace]).Distinct().Count() == 1); var targetNamespace = diagnostics.First().Properties[MatchFolderAndNamespaceConstants.TargetNamespace]; RoslynDebug.AssertNotNull(targetNamespace); // Use the Renamer.RenameDocumentAsync API to sync namespaces in the document. This allows // us to keep in line with the sync methodology that we have as a public API and not have // to rewrite or move the complex logic. RenameDocumentAsync is designed to behave the same // as the intent of this analyzer/codefix pair. var targetFolders = PathMetadataUtilities.BuildFoldersFromNamespace(targetNamespace, document.Project.DefaultNamespace); var documentWithInvalidFolders = document.WithFolders(document.Folders.Concat("Force-Namespace-Change")); var renameActionSet = await Renamer.RenameDocumentAsync( documentWithInvalidFolders, documentWithInvalidFolders.Name, newDocumentFolders: targetFolders, cancellationToken: cancellationToken).ConfigureAwait(false); var newSolution = await renameActionSet.UpdateSolutionAsync(documentWithInvalidFolders.Project.Solution, cancellationToken).ConfigureAwait(false); Debug.Assert(newSolution != document.Project.Solution); return newSolution; } public override FixAllProvider? GetFixAllProvider() => CustomFixAllProvider.Instance; private sealed class MyCodeAction : CustomCodeActions.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, 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/CSharp/Portable/Organizing/Organizers/ModifiersOrganizer.Comparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal partial class ModifiersOrganizer { private class Comparer : IComparer<SyntaxToken> { // TODO(cyrusn): Allow users to specify the ordering they want private enum Ordering { Accessibility, StaticInstance, Remainder } public int Compare(SyntaxToken x, SyntaxToken y) { if (x.Kind() == y.Kind()) { return 0; } return ComparerWithState.CompareTo(x, y, s_comparers); } private static readonly ImmutableArray<Func<SyntaxToken, IComparable>> s_comparers = ImmutableArray.Create<Func<SyntaxToken, IComparable>>(t => t.Kind() == SyntaxKind.PartialKeyword, t => GetOrdering(t)); private static Ordering GetOrdering(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.StaticKeyword: return Ordering.StaticInstance; case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.PublicKeyword: return Ordering.Accessibility; default: return Ordering.Remainder; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal partial class ModifiersOrganizer { private class Comparer : IComparer<SyntaxToken> { // TODO(cyrusn): Allow users to specify the ordering they want private enum Ordering { Accessibility, StaticInstance, Remainder } public int Compare(SyntaxToken x, SyntaxToken y) { if (x.Kind() == y.Kind()) { return 0; } return ComparerWithState.CompareTo(x, y, s_comparers); } private static readonly ImmutableArray<Func<SyntaxToken, IComparable>> s_comparers = ImmutableArray.Create<Func<SyntaxToken, IComparable>>(t => t.Kind() == SyntaxKind.PartialKeyword, t => GetOrdering(t)); private static Ordering GetOrdering(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.StaticKeyword: return Ordering.StaticInstance; case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.PublicKeyword: return Ordering.Accessibility; default: return Ordering.Remainder; } } } } }
-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/Emit/CodeGen/CodeGenStructsAndEnum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenStructsAndEnum : EmitMetadataTestBase { #region "Struct" [Fact] public void ValInstanceField() { string source = @" public class D { public struct Boo { public int I1; public static Boo Inst; } public static void Main() { Boo val = Boo.Inst; int i = val.I1; System.Console.Write(i); val.I1 = 42; System.Console.Write(val.I1); val.I1 = 7; System.Console.Write(val.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0427"); compilation.VerifyIL("D.Main", @" { // Code size 57 (0x39) .maxstack 2 .locals init (D.Boo V_0) //val IL_0000: ldsfld ""D.Boo D.Boo.Inst"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldfld ""int D.Boo.I1"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldloca.s V_0 IL_0013: ldc.i4.s 42 IL_0015: stfld ""int D.Boo.I1"" IL_001a: ldloc.0 IL_001b: ldfld ""int D.Boo.I1"" IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldloca.s V_0 IL_0027: ldc.i4.7 IL_0028: stfld ""int D.Boo.I1"" IL_002d: ldloc.0 IL_002e: ldfld ""int D.Boo.I1"" IL_0033: call ""void System.Console.Write(int)"" IL_0038: ret } "); } [Fact] public void ValStaticField() { string source = @" public class D { public struct Boo { public int I1; public static Boo Inst; } public static void Main() { Boo val = Boo.Inst; System.Console.Write(Boo.Inst.I1); val.I1 = 42; Boo.Inst = val; System.Console.Write(Boo.Inst.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "042"); compilation.VerifyIL("D.Main", @"{ // Code size 52 (0x34) .maxstack 2 .locals init (D.Boo V_0) //val IL_0000: ldsfld ""D.Boo D.Boo.Inst"" IL_0005: stloc.0 IL_0006: ldsflda ""D.Boo D.Boo.Inst"" IL_000b: ldfld ""int D.Boo.I1"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ldloca.s V_0 IL_0017: ldc.i4.s 42 IL_0019: stfld ""int D.Boo.I1"" IL_001e: ldloc.0 IL_001f: stsfld ""D.Boo D.Boo.Inst"" IL_0024: ldsflda ""D.Boo D.Boo.Inst"" IL_0029: ldfld ""int D.Boo.I1"" IL_002e: call ""void System.Console.Write(int)"" IL_0033: ret } "); } [Fact] public void StructCtor() { string source = @" public class D { public static void Main() { System.Decimal val = 0m; System.Console.Write(val); val = new System.Decimal(7); System.Console.Write(val); val = new System.Decimal(); System.Console.Write(val); val = ((decimal)int.MaxValue + 1) * 4; // use the ctor that takes a long System.Console.Write(val); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0708589934592"); // expect just two locals (temp is reused) compilation.VerifyIL("D.Main", @" { // Code size 51 (0x33) .maxstack 1 IL_0000: ldsfld ""decimal decimal.Zero"" IL_0005: call ""void System.Console.Write(decimal)"" IL_000a: ldc.i4.7 IL_000b: newobj ""decimal..ctor(int)"" IL_0010: call ""void System.Console.Write(decimal)"" IL_0015: ldsfld ""decimal decimal.Zero"" IL_001a: call ""void System.Console.Write(decimal)"" IL_001f: ldc.i8 0x200000000 IL_0028: newobj ""decimal..ctor(long)"" IL_002d: call ""void System.Console.Write(decimal)"" IL_0032: ret } "); } [Fact] public void AddressUnbox() { string source = @" using System; class Program { public struct S1 { public int x; public void Goo() { x = 123; } } public static S1 goo() { return new S1(); } static void Main() { goo().ToString(); Console.Write(goo().x); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0"); compilation.VerifyIL("Program.Main", @"{ // Code size 36 (0x24) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: call ""Program.S1 Program.goo()"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. ""Program.S1"" IL_000e: callvirt ""string object.ToString()"" IL_0013: pop IL_0014: call ""Program.S1 Program.goo()"" IL_0019: ldfld ""int Program.S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret } "); } [Fact] public void EqualsHashcode() { string source = @" using System; struct S1 { public int field; public override bool Equals(object obj) { return obj is S1 && field == ((S1)obj).field; } public override int GetHashCode() { return field; } public static bool operator ==(S1 value1, S1 value2) { return value1.field == value2.field; } public static bool operator !=(S1 value1, S1 value2) { return value1.field != value2.field; } } class Program { static void Main(string[] args) { } } "; var compilation = CompileAndVerify(source, expectedOutput: @""); compilation.VerifyIL("S1.Equals(object)", @" { // Code size 30 (0x1e) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S1"" IL_0006: brfalse.s IL_001c IL_0008: ldarg.0 IL_0009: ldfld ""int S1.field"" IL_000e: ldarg.1 IL_000f: unbox ""S1"" IL_0014: ldfld ""int S1.field"" IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret } ").VerifyIL("S1.GetHashCode()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ret } ").VerifyIL("bool S1.op_Equality(S1, S1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ldarg.1 IL_0007: ldfld ""int S1.field"" IL_000c: ceq IL_000e: ret } ").VerifyIL("bool S1.op_Inequality(S1, S1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ldarg.1 IL_0007: ldfld ""int S1.field"" IL_000c: ceq IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } "); } [Fact] public void EmitObjectGetTypeCallOnStruct() { string source = @" using System; class Program { public struct S1 { } static void Main() { Console.Write((new S1()).GetType()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+S1"); compilation.VerifyIL("Program.Main", @"{ // Code size 25 (0x19) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""Program.S1"" IL_0008: ldloc.0 IL_0009: box ""Program.S1"" IL_000e: call ""System.Type object.GetType()"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret } "); } [Fact] public void EmitInterfaceMethodOnStruct() { string source = @" using System; class Program { interface I { void M(); } struct S : I { public void M() { Console.WriteLine(""S::M""); } } static void Main(string[] args) { S s = new S(); s.M(); ((I)s).M(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"S::M S::M"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (Program.S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""Program.S"" IL_0008: ldloca.s V_0 IL_000a: call ""void Program.S.M()"" IL_000f: ldloc.0 IL_0010: box ""Program.S"" IL_0015: callvirt ""void Program.I.M()"" IL_001a: ret } "); } [Fact] public void ValueTypeWithGeneric() { string source = @" namespace NS { using System; using N2; namespace N2 { public interface IGoo<T> { void M(T t); } struct S<T, V> : IGoo<T> { public S(V v) { field = v; } public V field; public void M(T t) { Console.WriteLine(t); } } } public class Test { static S<N2, char>[] ary; class N1 { } class N2 : N1 { } static void Main() { IGoo<string> goo = new S<string, byte>(255); goo.M(""Abc""); Console.WriteLine(((S<string, byte>)goo).field); ary = new S<N2, char>[3]; ary[0] = ary[1] = ary[2] = new S<N2, char>('q'); Console.WriteLine(ary[1].field); } } } "; var compilation = CompileAndVerify(source, expectedOutput: @" Abc 255 q"); compilation.VerifyIL("NS.Test.Main", @"{ // Code size 120 (0x78) .maxstack 8 .locals init (NS.N2.S<NS.Test.N2, char> V_0) IL_0000: ldc.i4 0xff IL_0005: newobj ""NS.N2.S<string, byte>..ctor(byte)"" IL_000a: box ""NS.N2.S<string, byte>"" IL_000f: dup IL_0010: ldstr ""Abc"" IL_0015: callvirt ""void NS.N2.IGoo<string>.M(string)"" IL_001a: unbox ""NS.N2.S<string, byte>"" IL_001f: ldfld ""byte NS.N2.S<string, byte>.field"" IL_0024: call ""void System.Console.WriteLine(int)"" IL_0029: ldc.i4.3 IL_002a: newarr ""NS.N2.S<NS.Test.N2, char>"" IL_002f: stsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0034: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0039: ldc.i4.0 IL_003a: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_003f: ldc.i4.1 IL_0040: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0045: ldc.i4.2 IL_0046: ldc.i4.s 113 IL_0048: newobj ""NS.N2.S<NS.Test.N2, char>..ctor(char)"" IL_004d: dup IL_004e: stloc.0 IL_004f: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_0054: ldloc.0 IL_0055: dup IL_0056: stloc.0 IL_0057: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_005c: ldloc.0 IL_005d: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_0062: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0067: ldc.i4.1 IL_0068: ldelema ""NS.N2.S<NS.Test.N2, char>"" IL_006d: ldfld ""char NS.N2.S<NS.Test.N2, char>.field"" IL_0072: call ""void System.Console.WriteLine(char)"" IL_0077: ret } "); } [WorkItem(540954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540954")] [Fact] public void StructInit() { var text = @" struct Struct { public static void Main() { Struct s = new Struct(); } } "; string expectedIL = @" { // Code size 10 (0xa) .maxstack 1 .locals init (Struct V_0) //s IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""Struct"" IL_0009: ret } "; CompileAndVerify(text, options: TestOptions.DebugExe).VerifyIL("Struct.Main()", expectedIL); } [WorkItem(541845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541845")] [Fact] public void ConstructEnum() { var text = @" using System; class A { enum E1 { AA } static void Main() { var v = new DayOfWeek(); Console.Write(v.ToString()); var e = new E1(); Console.WriteLine(e.ToString()); } } "; string expectedIL = @" { // Code size 41 (0x29) .maxstack 1 .locals init (System.DayOfWeek V_0, //v A.E1 V_1) //e IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: constrained. ""System.DayOfWeek"" IL_000a: callvirt ""string object.ToString()"" IL_000f: call ""void System.Console.Write(string)"" IL_0014: ldc.i4.0 IL_0015: stloc.1 IL_0016: ldloca.s V_1 IL_0018: constrained. ""A.E1"" IL_001e: callvirt ""string object.ToString()"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ret }"; CompileAndVerify(text, expectedOutput: "SundayAA").VerifyIL("A.Main()", expectedIL); } [WorkItem(541599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541599")] [Fact] public void TestStructWithStaticField01() { var source = @" using System; public struct S { public static int _verify = 123; static void Main() { Console.Write(_verify); } } "; CompileAndVerify(source, expectedOutput: @"123"); } [Fact, WorkItem(543088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543088")] public void UseStructLocal() { var text = @" using System; struct GetProperty { int i; GetProperty(int x) { i = x; } static void Main() { GetProperty t = new GetProperty(123); Console.Write(t.i); } } "; CompileAndVerify(text, expectedOutput: "123"); } [Fact] public void InplaceInit001() { string source = @" public class D { public struct Boo { public int I1; } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { v1 = default(Boo); DummyUse(v1); Boo v2 = default(Boo); DummyUse(v2); rArg = default(Boo); DummyUse(rArg); vArg = default(Boo); DummyUse(rArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 73 (0x49) .maxstack 1 .locals init (D.Boo V_0) IL_0000: ldsflda ""D.Boo D.v1"" IL_0005: initobj ""D.Boo"" IL_000b: ldsfld ""D.Boo D.v1"" IL_0010: call ""void D.DummyUse(D.Boo)"" IL_0015: ldloca.s V_0 IL_0017: initobj ""D.Boo"" IL_001d: ldloc.0 IL_001e: call ""void D.DummyUse(D.Boo)"" IL_0023: ldarg.0 IL_0024: initobj ""D.Boo"" IL_002a: ldarg.0 IL_002b: ldobj ""D.Boo"" IL_0030: call ""void D.DummyUse(D.Boo)"" IL_0035: ldarga.s V_1 IL_0037: initobj ""D.Boo"" IL_003d: ldarg.0 IL_003e: ldobj ""D.Boo"" IL_0043: call ""void D.DummyUse(D.Boo)"" IL_0048: ret } "); } [Fact] public void InplaceInit002() { string source = @" public class D { public struct Boo { public int I1; } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { try { v1 = default(Boo); DummyUse(v1); Boo v2 = default(Boo); DummyUse(v2); rArg = default(Boo); DummyUse(rArg); vArg = default(Boo); DummyUse(rArg); } catch (System.Exception) { rArg = default(Boo); DummyUse(rArg); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 96 (0x60) .maxstack 1 .locals init (D.Boo V_0) .try { IL_0000: ldsflda ""D.Boo D.v1"" IL_0005: initobj ""D.Boo"" IL_000b: ldsfld ""D.Boo D.v1"" IL_0010: call ""void D.DummyUse(D.Boo)"" IL_0015: ldloca.s V_0 IL_0017: initobj ""D.Boo"" IL_001d: ldloc.0 IL_001e: call ""void D.DummyUse(D.Boo)"" IL_0023: ldarg.0 IL_0024: initobj ""D.Boo"" IL_002a: ldarg.0 IL_002b: ldobj ""D.Boo"" IL_0030: call ""void D.DummyUse(D.Boo)"" IL_0035: ldarga.s V_1 IL_0037: initobj ""D.Boo"" IL_003d: ldarg.0 IL_003e: ldobj ""D.Boo"" IL_0043: call ""void D.DummyUse(D.Boo)"" IL_0048: leave.s IL_005f } catch System.Exception { IL_004a: pop IL_004b: ldarg.0 IL_004c: initobj ""D.Boo"" IL_0052: ldarg.0 IL_0053: ldobj ""D.Boo"" IL_0058: call ""void D.DummyUse(D.Boo)"" IL_005d: leave.s IL_005f } IL_005f: ret } "); } [Fact] public void InplaceCtor001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { //try //{ v1 = new Boo(42); DummyUse(v1); Boo v2 = new Boo(42); DummyUse(v2); rArg = new Boo(42); DummyUse(rArg); vArg = new Boo(42); DummyUse(rArg); //} //catch (System.Exception) // // rArg = new Boo(42); // DummyUse(rArg); //} } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 79 (0x4f) .maxstack 2 IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: stsfld ""D.Boo D.v1"" IL_000c: ldsfld ""D.Boo D.v1"" IL_0011: call ""void D.DummyUse(D.Boo)"" IL_0016: ldc.i4.s 42 IL_0018: newobj ""D.Boo..ctor(int)"" IL_001d: call ""void D.DummyUse(D.Boo)"" IL_0022: ldarg.0 IL_0023: ldc.i4.s 42 IL_0025: newobj ""D.Boo..ctor(int)"" IL_002a: stobj ""D.Boo"" IL_002f: ldarg.0 IL_0030: ldobj ""D.Boo"" IL_0035: call ""void D.DummyUse(D.Boo)"" IL_003a: ldarga.s V_1 IL_003c: ldc.i4.s 42 IL_003e: call ""D.Boo..ctor(int)"" IL_0043: ldarg.0 IL_0044: ldobj ""D.Boo"" IL_0049: call ""void D.DummyUse(D.Boo)"" IL_004e: ret } "); } [Fact] public void InplaceCtor002() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { Boo v3; try{ Boo v3a; try { v1 = new Boo(42); DummyUse(v1); Boo v2 = new Boo(43); DummyUse(v2); v3 = new Boo(44); v3.ToString(); // should be a call, since v4 is defined in the same try scope Boo v4 = new Boo(45); v4.ToString(); rArg = new Boo(46); DummyUse(rArg); vArg = new Boo(47); DummyUse(rArg); } catch (System.Exception) { v3 = new Boo(44); v3.ToString(); // should be a call, since v3a is defined in the same try scope v3a = new Boo(44); v3a.ToString(); // should be a call, since v4 is defined in the same try scope Boo v4 = new Boo(45); v4.ToString(); rArg = new Boo(48); DummyUse(rArg); } } finally { } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 222 (0xde) .maxstack 2 .locals init (D.Boo V_0, //v3 D.Boo V_1, //v3a D.Boo V_2, //v4 D.Boo V_3) //v4 .try { IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: stsfld ""D.Boo D.v1"" IL_000c: ldsfld ""D.Boo D.v1"" IL_0011: call ""void D.DummyUse(D.Boo)"" IL_0016: ldc.i4.s 43 IL_0018: newobj ""D.Boo..ctor(int)"" IL_001d: call ""void D.DummyUse(D.Boo)"" IL_0022: ldc.i4.s 44 IL_0024: newobj ""D.Boo..ctor(int)"" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""D.Boo"" IL_0032: callvirt ""string object.ToString()"" IL_0037: pop IL_0038: ldloca.s V_2 IL_003a: ldc.i4.s 45 IL_003c: call ""D.Boo..ctor(int)"" IL_0041: ldloca.s V_2 IL_0043: constrained. ""D.Boo"" IL_0049: callvirt ""string object.ToString()"" IL_004e: pop IL_004f: ldarg.0 IL_0050: ldc.i4.s 46 IL_0052: newobj ""D.Boo..ctor(int)"" IL_0057: stobj ""D.Boo"" IL_005c: ldarg.0 IL_005d: ldobj ""D.Boo"" IL_0062: call ""void D.DummyUse(D.Boo)"" IL_0067: ldc.i4.s 47 IL_0069: newobj ""D.Boo..ctor(int)"" IL_006e: starg.s V_1 IL_0070: ldarg.0 IL_0071: ldobj ""D.Boo"" IL_0076: call ""void D.DummyUse(D.Boo)"" IL_007b: leave.s IL_00dd } catch System.Exception { IL_007d: pop IL_007e: ldloca.s V_0 IL_0080: ldc.i4.s 44 IL_0082: call ""D.Boo..ctor(int)"" IL_0087: ldloca.s V_0 IL_0089: constrained. ""D.Boo"" IL_008f: callvirt ""string object.ToString()"" IL_0094: pop IL_0095: ldloca.s V_1 IL_0097: ldc.i4.s 44 IL_0099: call ""D.Boo..ctor(int)"" IL_009e: ldloca.s V_1 IL_00a0: constrained. ""D.Boo"" IL_00a6: callvirt ""string object.ToString()"" IL_00ab: pop IL_00ac: ldloca.s V_3 IL_00ae: ldc.i4.s 45 IL_00b0: call ""D.Boo..ctor(int)"" IL_00b5: ldloca.s V_3 IL_00b7: constrained. ""D.Boo"" IL_00bd: callvirt ""string object.ToString()"" IL_00c2: pop IL_00c3: ldarg.0 IL_00c4: ldc.i4.s 48 IL_00c6: newobj ""D.Boo..ctor(int)"" IL_00cb: stobj ""D.Boo"" IL_00d0: ldarg.0 IL_00d1: ldobj ""D.Boo"" IL_00d6: call ""void D.DummyUse(D.Boo)"" IL_00db: leave.s IL_00dd } IL_00dd: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [Fact] public void InplaceCtor003() { string source = @" public class D { public struct Boo { public int I1; public Boo(ref int i1) { this.I1 = 1; this.I1 += i1; } public Boo(ref Boo b1) { this.I1 = 1; this.I1 += b1.I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); a1 = new Boo(ref a1); System.Console.Write(a1.I1); v1 = new Boo(ref v1); System.Console.Write(v1.I1); a1 = default(Boo); v1 = default(Boo); a1 = new Boo(ref a1.I1); System.Console.Write(a1.I1); v1 = new Boo(ref v1.I1); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "1111"); compilation.VerifyIL("D.Main", @" { // Code size 136 (0x88) .maxstack 1 .locals init (D.Boo V_0) //a1 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldloca.s V_0 IL_000a: newobj ""D.Boo..ctor(ref D.Boo)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: ldfld ""int D.Boo.I1"" IL_0016: call ""void System.Console.Write(int)"" IL_001b: ldsflda ""D.Boo D.v1"" IL_0020: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0025: stsfld ""D.Boo D.v1"" IL_002a: ldsflda ""D.Boo D.v1"" IL_002f: ldfld ""int D.Boo.I1"" IL_0034: call ""void System.Console.Write(int)"" IL_0039: ldloca.s V_0 IL_003b: initobj ""D.Boo"" IL_0041: ldsflda ""D.Boo D.v1"" IL_0046: initobj ""D.Boo"" IL_004c: ldloca.s V_0 IL_004e: ldflda ""int D.Boo.I1"" IL_0053: newobj ""D.Boo..ctor(ref int)"" IL_0058: stloc.0 IL_0059: ldloc.0 IL_005a: ldfld ""int D.Boo.I1"" IL_005f: call ""void System.Console.Write(int)"" IL_0064: ldsflda ""D.Boo D.v1"" IL_0069: ldflda ""int D.Boo.I1"" IL_006e: newobj ""D.Boo..ctor(ref int)"" IL_0073: stsfld ""D.Boo D.v1"" IL_0078: ldsflda ""D.Boo D.v1"" IL_007d: ldfld ""int D.Boo.I1"" IL_0082: call ""void System.Console.Write(int)"" IL_0087: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [Fact] public void InplaceCtor004() { string source = @" public class D { public struct Boo { public int I1; public Boo(ref int i1) { this.I1 = 1; this.I1 += i1; } public Boo(ref Boo b1) { this.I1 = 1; this.I1 += b1.I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); ref var r1 = ref a1; a1 = new Boo(ref r1); System.Console.Write(a1.I1); ref var r2 = ref v1; v1 = new Boo(ref r2); System.Console.Write(v1.I1); a1 = default(Boo); v1 = default(Boo); ref var r3 = ref a1.I1; a1 = new Boo(ref r3); System.Console.Write(a1.I1); ref var r4 = ref v1.I1; v1 = new Boo(ref r4); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "1111"); compilation.VerifyIL("D.Main", @" { // Code size 146 (0x92) .maxstack 1 .locals init (D.Boo V_0, //a1 D.Boo& V_1, //r1 D.Boo& V_2, //r2 int& V_3, //r3 int& V_4) //r4 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldloca.s V_0 IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldfld ""int D.Boo.I1"" IL_0018: call ""void System.Console.Write(int)"" IL_001d: ldsflda ""D.Boo D.v1"" IL_0022: stloc.2 IL_0023: ldloc.2 IL_0024: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0029: stsfld ""D.Boo D.v1"" IL_002e: ldsflda ""D.Boo D.v1"" IL_0033: ldfld ""int D.Boo.I1"" IL_0038: call ""void System.Console.Write(int)"" IL_003d: ldloca.s V_0 IL_003f: initobj ""D.Boo"" IL_0045: ldsflda ""D.Boo D.v1"" IL_004a: initobj ""D.Boo"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""int D.Boo.I1"" IL_0057: stloc.3 IL_0058: ldloc.3 IL_0059: newobj ""D.Boo..ctor(ref int)"" IL_005e: stloc.0 IL_005f: ldloc.0 IL_0060: ldfld ""int D.Boo.I1"" IL_0065: call ""void System.Console.Write(int)"" IL_006a: ldsflda ""D.Boo D.v1"" IL_006f: ldflda ""int D.Boo.I1"" IL_0074: stloc.s V_4 IL_0076: ldloc.s V_4 IL_0078: newobj ""D.Boo..ctor(ref int)"" IL_007d: stsfld ""D.Boo D.v1"" IL_0082: ldsflda ""D.Boo D.v1"" IL_0087: ldfld ""int D.Boo.I1"" IL_008c: call ""void System.Console.Write(int)"" IL_0091: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void InplaceCtor005() { string source = @" using System; public class D { public struct Boo { public int I1; public Boo(int x, __arglist) { this.I1 = 1; this.I1 += __refvalue(new ArgIterator(__arglist).GetNextArg(), Boo).I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); a1 = new Boo(1, __arglist(ref a1)); System.Console.Write(a1.I1); v1 = new Boo(1, __arglist(ref v1)); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "11"); compilation.VerifyIL("D.Main", @" { // Code size 60 (0x3c) .maxstack 2 .locals init (D.Boo V_0) //a1 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldc.i4.1 IL_0009: ldloca.s V_0 IL_000b: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldfld ""int D.Boo.I1"" IL_0017: call ""void System.Console.Write(int)"" IL_001c: ldc.i4.1 IL_001d: ldsflda ""D.Boo D.v1"" IL_0022: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)"" IL_0027: stsfld ""D.Boo D.v1"" IL_002c: ldsflda ""D.Boo D.v1"" IL_0031: ldfld ""int D.Boo.I1"" IL_0036: call ""void System.Console.Write(int)"" IL_003b: ret } "); } [Fact] public void InitUsed001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void DummyUse1(ref Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { DummyUse(v1 = default(Boo)); DummyUse(v1); Boo v2; DummyUse(v2 = default(Boo)); DummyUse(v2); // TODO: no need for a temp Boo v2a; DummyUse(v2a = default(Boo)); DummyUse1(ref v2a); DummyUse(rArg = default(Boo)); DummyUse(rArg); // TODO: no need for a temp DummyUse(vArg = default(Boo)); DummyUse(vArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 126 (0x7e) .maxstack 3 .locals init (D.Boo V_0, //v2a D.Boo V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""D.Boo"" IL_0008: ldloc.1 IL_0009: dup IL_000a: stsfld ""D.Boo D.v1"" IL_000f: call ""void D.DummyUse(D.Boo)"" IL_0014: ldsfld ""D.Boo D.v1"" IL_0019: call ""void D.DummyUse(D.Boo)"" IL_001e: ldloca.s V_1 IL_0020: initobj ""D.Boo"" IL_0026: ldloc.1 IL_0027: dup IL_0028: call ""void D.DummyUse(D.Boo)"" IL_002d: call ""void D.DummyUse(D.Boo)"" IL_0032: ldloca.s V_0 IL_0034: initobj ""D.Boo"" IL_003a: ldloc.0 IL_003b: call ""void D.DummyUse(D.Boo)"" IL_0040: ldloca.s V_0 IL_0042: call ""void D.DummyUse1(ref D.Boo)"" IL_0047: ldarg.0 IL_0048: ldloca.s V_1 IL_004a: initobj ""D.Boo"" IL_0050: ldloc.1 IL_0051: dup IL_0052: stloc.1 IL_0053: stobj ""D.Boo"" IL_0058: ldloc.1 IL_0059: call ""void D.DummyUse(D.Boo)"" IL_005e: ldarg.0 IL_005f: ldobj ""D.Boo"" IL_0064: call ""void D.DummyUse(D.Boo)"" IL_0069: ldarga.s V_1 IL_006b: initobj ""D.Boo"" IL_0071: ldarg.1 IL_0072: call ""void D.DummyUse(D.Boo)"" IL_0077: ldarg.1 IL_0078: call ""void D.DummyUse(D.Boo)"" IL_007d: ret } "); } [Fact] public void CtorUsed001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void DummyUse1(ref Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { DummyUse(v1 = new Boo(42)); DummyUse(v1); Boo v2; DummyUse(v2 = new Boo(42)); DummyUse(v2); Boo v2a; DummyUse(v2a = new Boo(42)); DummyUse1(ref v2a); DummyUse(rArg = new Boo(42)); DummyUse(rArg); DummyUse(vArg = new Boo(42)); DummyUse(vArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 122 (0x7a) .maxstack 3 .locals init (D.Boo V_0, //v2a D.Boo V_1) IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: dup IL_0008: stsfld ""D.Boo D.v1"" IL_000d: call ""void D.DummyUse(D.Boo)"" IL_0012: ldsfld ""D.Boo D.v1"" IL_0017: call ""void D.DummyUse(D.Boo)"" IL_001c: ldc.i4.s 42 IL_001e: newobj ""D.Boo..ctor(int)"" IL_0023: dup IL_0024: call ""void D.DummyUse(D.Boo)"" IL_0029: call ""void D.DummyUse(D.Boo)"" IL_002e: ldloca.s V_0 IL_0030: ldc.i4.s 42 IL_0032: call ""D.Boo..ctor(int)"" IL_0037: ldloc.0 IL_0038: call ""void D.DummyUse(D.Boo)"" IL_003d: ldloca.s V_0 IL_003f: call ""void D.DummyUse1(ref D.Boo)"" IL_0044: ldarg.0 IL_0045: ldc.i4.s 42 IL_0047: newobj ""D.Boo..ctor(int)"" IL_004c: dup IL_004d: stloc.1 IL_004e: stobj ""D.Boo"" IL_0053: ldloc.1 IL_0054: call ""void D.DummyUse(D.Boo)"" IL_0059: ldarg.0 IL_005a: ldobj ""D.Boo"" IL_005f: call ""void D.DummyUse(D.Boo)"" IL_0064: ldarga.s V_1 IL_0066: ldc.i4.s 42 IL_0068: call ""D.Boo..ctor(int)"" IL_006d: ldarg.1 IL_006e: call ""void D.DummyUse(D.Boo)"" IL_0073: ldarg.1 IL_0074: call ""void D.DummyUse(D.Boo)"" IL_0079: ret } "); } [Fact] public void InheritedCallOnReadOnly() { string source = @" class Program { static void Main() { var obj = new C1(); System.Console.WriteLine(obj.field.ToString()); } } class C1 { public readonly S1 field; } struct S1 { } "; var compilation = CompileAndVerify(source, expectedOutput: "S1", verify: Verification.Skipped); compilation.VerifyIL("Program.Main", @" { // Code size 27 (0x1b) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ldflda ""S1 C1.field"" IL_000a: constrained. ""S1"" IL_0010: callvirt ""string object.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ret } "); compilation = CompileAndVerify(source, expectedOutput: "S1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); compilation.VerifyIL("Program.Main", @" { // Code size 30 (0x1e) .maxstack 1 .locals init (S1 V_0) IL_0000: newobj ""C1..ctor()"" IL_0005: ldfld ""S1 C1.field"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: constrained. ""S1"" IL_0013: callvirt ""string object.ToString()"" IL_0018: call ""void System.Console.WriteLine(string)"" IL_001d: ret } "); } [Fact] [WorkItem(27049, "https://github.com/dotnet/roslyn/issues/27049")] public void BoxingRefStructForBaseCall() { CreateCompilation(@" ref struct S { public override bool Equals(object obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); public override string ToString() => base.ToString(); }").VerifyDiagnostics( // (4,48): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override bool Equals(object obj) => base.Equals(obj); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(4, 48), // (6,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override int GetHashCode() => base.GetHashCode(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(6, 42), // (8,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override string ToString() => base.ToString(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(8, 42)); } #endregion #region "Enum" [Fact] public void TestEnum() { string source = @"enum E { A, B } class C { static void Main() { E e = E.A; e = e + 1; } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("C.Main", @"{ // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: pop IL_0002: ret } "); } [Fact] public void BoxEnum() { string source = @"enum E { A, B } class C { static void Main() { E e = E.B; object o = e; e = (E)o; System.Console.Write(e); } } "; var compilation = CompileAndVerify(source, expectedOutput: "B"); compilation.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""E"" IL_0006: unbox.any ""E"" IL_000b: box ""E"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ret } "); } [Fact] public void MBRO_StructField() { string source = @" using System; class Program { static void Main(string[] args) { var v = new cls1(); v.Test(); } } struct S1 { public Guid g; } class cls1 : MarshalByRefObject { public Guid g1; public S1 s; public void Test() { g1 = new Guid(); TestRef(ref g1); g1 = new Guid(g1.ToString()); System.Console.WriteLine(g1); System.Console.WriteLine(s.g.ToString()); var other = new cls1(); other.g1 = new Guid(); System.Console.WriteLine(other.g1); TestRef(ref other.g1); other.g1 = new Guid(other.g1.ToString()); System.Console.WriteLine(other.g1); System.Console.WriteLine(other.s.g.ToString()); var gg = other.s.g; System.Console.WriteLine(gg); } public void TestRef(ref Guid arg) { arg = new Guid(""ca761232ed4211cebacd00aa0057b223""); } } "; var compilation = CompileAndVerify(source, expectedOutput: @"ca761232-ed42-11ce-bacd-00aa0057b223 00000000-0000-0000-0000-000000000000 00000000-0000-0000-0000-000000000000 ca761232-ed42-11ce-bacd-00aa0057b223 00000000-0000-0000-0000-000000000000 00000000-0000-0000-0000-000000000000"); compilation.VerifyIL("cls1.Test", @" { // Code size 237 (0xed) .maxstack 2 .locals init (cls1 V_0, //other System.Guid V_1) IL_0000: ldarg.0 IL_0001: ldflda ""System.Guid cls1.g1"" IL_0006: initobj ""System.Guid"" IL_000c: ldarg.0 IL_000d: ldarg.0 IL_000e: ldflda ""System.Guid cls1.g1"" IL_0013: call ""void cls1.TestRef(ref System.Guid)"" IL_0018: ldarg.0 IL_0019: ldarg.0 IL_001a: ldflda ""System.Guid cls1.g1"" IL_001f: constrained. ""System.Guid"" IL_0025: callvirt ""string object.ToString()"" IL_002a: newobj ""System.Guid..ctor(string)"" IL_002f: stfld ""System.Guid cls1.g1"" IL_0034: ldarg.0 IL_0035: ldfld ""System.Guid cls1.g1"" IL_003a: box ""System.Guid"" IL_003f: call ""void System.Console.WriteLine(object)"" IL_0044: ldarg.0 IL_0045: ldflda ""S1 cls1.s"" IL_004a: ldflda ""System.Guid S1.g"" IL_004f: constrained. ""System.Guid"" IL_0055: callvirt ""string object.ToString()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: newobj ""cls1..ctor()"" IL_0064: stloc.0 IL_0065: ldloc.0 IL_0066: ldloca.s V_1 IL_0068: initobj ""System.Guid"" IL_006e: ldloc.1 IL_006f: stfld ""System.Guid cls1.g1"" IL_0074: ldloc.0 IL_0075: ldfld ""System.Guid cls1.g1"" IL_007a: box ""System.Guid"" IL_007f: call ""void System.Console.WriteLine(object)"" IL_0084: ldarg.0 IL_0085: ldloc.0 IL_0086: ldflda ""System.Guid cls1.g1"" IL_008b: call ""void cls1.TestRef(ref System.Guid)"" IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldflda ""System.Guid cls1.g1"" IL_0097: constrained. ""System.Guid"" IL_009d: callvirt ""string object.ToString()"" IL_00a2: newobj ""System.Guid..ctor(string)"" IL_00a7: stfld ""System.Guid cls1.g1"" IL_00ac: ldloc.0 IL_00ad: ldfld ""System.Guid cls1.g1"" IL_00b2: box ""System.Guid"" IL_00b7: call ""void System.Console.WriteLine(object)"" IL_00bc: ldloc.0 IL_00bd: ldflda ""S1 cls1.s"" IL_00c2: ldflda ""System.Guid S1.g"" IL_00c7: constrained. ""System.Guid"" IL_00cd: callvirt ""string object.ToString()"" IL_00d2: call ""void System.Console.WriteLine(string)"" IL_00d7: ldloc.0 IL_00d8: ldfld ""S1 cls1.s"" IL_00dd: ldfld ""System.Guid S1.g"" IL_00e2: box ""System.Guid"" IL_00e7: call ""void System.Console.WriteLine(object)"" IL_00ec: ret } "); } [Fact] public void InitTemp001() { string source = @" using System; struct S { int x; static void Main() { Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.x"" IL_0010: ldloca.s V_0 IL_0012: ldloca.s V_1 IL_0014: initobj ""S"" IL_001a: ldloca.s V_1 IL_001c: ldc.i4.1 IL_001d: stfld ""int S.x"" IL_0022: ldloc.1 IL_0023: box ""S"" IL_0028: constrained. ""S"" IL_002e: callvirt ""bool object.Equals(object)"" IL_0033: call ""void System.Console.WriteLine(bool)"" IL_0038: ret } "); } [Fact] public void InitTemp001a() { string source = @" using System; struct S1 { public int x; } struct S { public S1 x; static void Main() { Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 94 (0x5e) .maxstack 4 .locals init (S V_0, S1 V_1, S V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: initobj ""S1"" IL_0012: ldloca.s V_1 IL_0014: ldc.i4.0 IL_0015: stfld ""int S1.x"" IL_001a: ldloc.1 IL_001b: stfld ""S1 S.x"" IL_0020: ldloca.s V_0 IL_0022: ldflda ""S1 S.x"" IL_0027: ldloca.s V_2 IL_0029: initobj ""S"" IL_002f: ldloca.s V_2 IL_0031: ldloca.s V_1 IL_0033: initobj ""S1"" IL_0039: ldloca.s V_1 IL_003b: ldc.i4.1 IL_003c: stfld ""int S1.x"" IL_0041: ldloc.1 IL_0042: stfld ""S1 S.x"" IL_0047: ldloc.2 IL_0048: box ""S"" IL_004d: constrained. ""S1"" IL_0053: callvirt ""bool object.Equals(object)"" IL_0058: call ""void System.Console.WriteLine(bool)"" IL_005d: ret } "); } [Fact] public void InitTemp001b() { string source = @" using System; class S1 { public int x; } struct S { public S1 x; static void Main() { Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 77 (0x4d) .maxstack 5 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: newobj ""S1..ctor()"" IL_000f: dup IL_0010: ldc.i4.0 IL_0011: stfld ""int S1.x"" IL_0016: stfld ""S1 S.x"" IL_001b: ldloc.0 IL_001c: ldfld ""S1 S.x"" IL_0021: ldloca.s V_0 IL_0023: initobj ""S"" IL_0029: ldloca.s V_0 IL_002b: newobj ""S1..ctor()"" IL_0030: dup IL_0031: ldc.i4.1 IL_0032: stfld ""int S1.x"" IL_0037: stfld ""S1 S.x"" IL_003c: ldloc.0 IL_003d: box ""S"" IL_0042: callvirt ""bool object.Equals(object)"" IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ret } "); } [Fact] public void InitTemp002() { string source = @" using System; struct S { int x; static void Main() { Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }).Equals( new S { x = 1 }.Equals(new S { x = 1 }))); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 116 (0x74) .maxstack 4 .locals init (S V_0, S V_1, bool V_2, S V_3) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.x"" IL_0010: ldloca.s V_0 IL_0012: ldloca.s V_1 IL_0014: initobj ""S"" IL_001a: ldloca.s V_1 IL_001c: ldc.i4.1 IL_001d: stfld ""int S.x"" IL_0022: ldloc.1 IL_0023: box ""S"" IL_0028: constrained. ""S"" IL_002e: callvirt ""bool object.Equals(object)"" IL_0033: stloc.2 IL_0034: ldloca.s V_2 IL_0036: ldloca.s V_1 IL_0038: initobj ""S"" IL_003e: ldloca.s V_1 IL_0040: ldc.i4.1 IL_0041: stfld ""int S.x"" IL_0046: ldloca.s V_1 IL_0048: ldloca.s V_3 IL_004a: initobj ""S"" IL_0050: ldloca.s V_3 IL_0052: ldc.i4.1 IL_0053: stfld ""int S.x"" IL_0058: ldloc.3 IL_0059: box ""S"" IL_005e: constrained. ""S"" IL_0064: callvirt ""bool object.Equals(object)"" IL_0069: call ""bool bool.Equals(bool)"" IL_006e: call ""void System.Console.WriteLine(bool)"" IL_0073: ret } "); } [Fact] public void InitTemp003() { string source = @" using System; readonly struct S { readonly int x; public S(int x) { this.x = x; } static void Main() { // named argument reordering introduces a sequence with temps // and we cannot know whether RefMethod returns a ref to a sequence local // so we must assume that it can, and therefore must keep all the sequence the locals in use // for the duration of the most-encompassing expression. Console.WriteLine(RefMethod(arg2: I(5), arg1: I(3)).GreaterThan( RefMethod(arg2: I(0), arg1: I(0)))); } public static ref readonly S RefMethod(in S arg1, in S arg2) { return ref arg2; } public bool GreaterThan(in S arg) { return this.x > arg.x; } public static S I(int arg) { return new S(arg); } } "; var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: "True"); compilation.VerifyIL("S.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, S V_1, S V_2, S V_3) IL_0000: ldc.i4.5 IL_0001: call ""S S.I(int)"" IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: call ""S S.I(int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldloca.s V_0 IL_0012: call ""ref readonly S S.RefMethod(in S, in S)"" IL_0017: ldc.i4.0 IL_0018: call ""S S.I(int)"" IL_001d: stloc.2 IL_001e: ldc.i4.0 IL_001f: call ""S S.I(int)"" IL_0024: stloc.3 IL_0025: ldloca.s V_3 IL_0027: ldloca.s V_2 IL_0029: call ""ref readonly S S.RefMethod(in S, in S)"" IL_002e: call ""bool S.GreaterThan(in S)"" IL_0033: call ""void System.Console.WriteLine(bool)"" IL_0038: ret } "); } [Fact] public void InitTemp004() { string source = @" using System; readonly struct S { public readonly int x; public S(int x) { this.x = x; } static void Main() { System.Console.Write(TestRO().x); System.Console.WriteLine(); System.Console.Write(Test().x); } static ref readonly S TestRO() { try { // both args are refs return ref RefMethodRO(arg2: I(5), arg1: I(3)); } finally { // first arg is a value!! RefMethodRO(arg2: I_Val(5), arg1: I(3)); } } public static ref readonly S RefMethodRO(in S arg1, in S arg2) { System.Console.Write(arg2.x); return ref arg2; } // similar as above, but with regular (not readonly) refs for comparison static ref S Test() { try { return ref RefMethod(arg2: ref I(5), arg1: ref I(3)); } finally { var temp = I(5); RefMethod(arg2: ref temp, arg1: ref I(3)); } } public static ref S RefMethod(ref S arg1, ref S arg2) { System.Console.Write(arg2.x); return ref arg2; } private static S[] arr = new S[] { new S() }; public static ref S I(int arg) { arr[0] = new S(arg); return ref arr[0]; } public static S I_Val(int arg) { arr[0] = new S(arg); return arr[0]; } } "; var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: @"353 353"); compilation.VerifyIL("S.TestRO", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (S& V_0, S& V_1, S V_2) .try { IL_0000: ldc.i4.5 IL_0001: call ""ref S S.I(int)"" IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: call ""ref S S.I(int)"" IL_000d: ldloc.0 IL_000e: call ""ref readonly S S.RefMethodRO(in S, in S)"" IL_0013: stloc.1 IL_0014: leave.s IL_002c } finally { IL_0016: ldc.i4.5 IL_0017: call ""S S.I_Val(int)"" IL_001c: stloc.2 IL_001d: ldc.i4.3 IL_001e: call ""ref S S.I(int)"" IL_0023: ldloca.s V_2 IL_0025: call ""ref readonly S S.RefMethodRO(in S, in S)"" IL_002a: pop IL_002b: endfinally } IL_002c: ldloc.1 IL_002d: ret } "); } [WorkItem(842477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842477")] [Fact] public void DecimalConst() { string source = @" #pragma warning disable 458, 169, 414 using System; public class NullableTest { static decimal? NULL = null; public static void EqualEqual() { Test.Eval((decimal?)1m == null, false); Test.Eval((decimal?)1m == NULL, false); Test.Eval((decimal?)0 == NULL, false); } } public class Test { public static void Eval(object obj1, object obj2) { } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("NullableTest.EqualEqual", @" { // Code size 112 (0x70) .maxstack 2 .locals init (decimal? V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: ldc.i4.0 IL_0007: box ""bool"" IL_000c: call ""void Test.Eval(object, object)"" IL_0011: ldsfld ""decimal decimal.One"" IL_0016: ldsfld ""decimal? NullableTest.NULL"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: call ""decimal decimal?.GetValueOrDefault()"" IL_0023: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0028: ldloca.s V_0 IL_002a: call ""bool decimal?.HasValue.get"" IL_002f: and IL_0030: box ""bool"" IL_0035: ldc.i4.0 IL_0036: box ""bool"" IL_003b: call ""void Test.Eval(object, object)"" IL_0040: ldsfld ""decimal decimal.Zero"" IL_0045: ldsfld ""decimal? NullableTest.NULL"" IL_004a: stloc.0 IL_004b: ldloca.s V_0 IL_004d: call ""decimal decimal?.GetValueOrDefault()"" IL_0052: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0057: ldloca.s V_0 IL_0059: call ""bool decimal?.HasValue.get"" IL_005e: and IL_005f: box ""bool"" IL_0064: ldc.i4.0 IL_0065: box ""bool"" IL_006a: call ""void Test.Eval(object, object)"" IL_006f: ret } "); } [Fact] public void FieldLoad001() { string source = @" using System; struct Point { public int x; public int y; } class Rectangle { public Point topLeft; public Point bottomRight; } struct C1 { public C1(int i) { r = new Rectangle(); } public Rectangle r; } class Program { static object p = new C1(1); static void Main(string[] args) { System.Console.WriteLine(((C1)p).r.topLeft.x); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @" { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldsfld ""object Program.p"" IL_0005: unbox ""C1"" IL_000a: ldfld ""Rectangle C1.r"" IL_000f: ldflda ""Point Rectangle.topLeft"" IL_0014: ldfld ""int Point.x"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ret } "); } #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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenStructsAndEnum : EmitMetadataTestBase { #region "Struct" [Fact] public void ValInstanceField() { string source = @" public class D { public struct Boo { public int I1; public static Boo Inst; } public static void Main() { Boo val = Boo.Inst; int i = val.I1; System.Console.Write(i); val.I1 = 42; System.Console.Write(val.I1); val.I1 = 7; System.Console.Write(val.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0427"); compilation.VerifyIL("D.Main", @" { // Code size 57 (0x39) .maxstack 2 .locals init (D.Boo V_0) //val IL_0000: ldsfld ""D.Boo D.Boo.Inst"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldfld ""int D.Boo.I1"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldloca.s V_0 IL_0013: ldc.i4.s 42 IL_0015: stfld ""int D.Boo.I1"" IL_001a: ldloc.0 IL_001b: ldfld ""int D.Boo.I1"" IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldloca.s V_0 IL_0027: ldc.i4.7 IL_0028: stfld ""int D.Boo.I1"" IL_002d: ldloc.0 IL_002e: ldfld ""int D.Boo.I1"" IL_0033: call ""void System.Console.Write(int)"" IL_0038: ret } "); } [Fact] public void ValStaticField() { string source = @" public class D { public struct Boo { public int I1; public static Boo Inst; } public static void Main() { Boo val = Boo.Inst; System.Console.Write(Boo.Inst.I1); val.I1 = 42; Boo.Inst = val; System.Console.Write(Boo.Inst.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "042"); compilation.VerifyIL("D.Main", @"{ // Code size 52 (0x34) .maxstack 2 .locals init (D.Boo V_0) //val IL_0000: ldsfld ""D.Boo D.Boo.Inst"" IL_0005: stloc.0 IL_0006: ldsflda ""D.Boo D.Boo.Inst"" IL_000b: ldfld ""int D.Boo.I1"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ldloca.s V_0 IL_0017: ldc.i4.s 42 IL_0019: stfld ""int D.Boo.I1"" IL_001e: ldloc.0 IL_001f: stsfld ""D.Boo D.Boo.Inst"" IL_0024: ldsflda ""D.Boo D.Boo.Inst"" IL_0029: ldfld ""int D.Boo.I1"" IL_002e: call ""void System.Console.Write(int)"" IL_0033: ret } "); } [Fact] public void StructCtor() { string source = @" public class D { public static void Main() { System.Decimal val = 0m; System.Console.Write(val); val = new System.Decimal(7); System.Console.Write(val); val = new System.Decimal(); System.Console.Write(val); val = ((decimal)int.MaxValue + 1) * 4; // use the ctor that takes a long System.Console.Write(val); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0708589934592"); // expect just two locals (temp is reused) compilation.VerifyIL("D.Main", @" { // Code size 51 (0x33) .maxstack 1 IL_0000: ldsfld ""decimal decimal.Zero"" IL_0005: call ""void System.Console.Write(decimal)"" IL_000a: ldc.i4.7 IL_000b: newobj ""decimal..ctor(int)"" IL_0010: call ""void System.Console.Write(decimal)"" IL_0015: ldsfld ""decimal decimal.Zero"" IL_001a: call ""void System.Console.Write(decimal)"" IL_001f: ldc.i8 0x200000000 IL_0028: newobj ""decimal..ctor(long)"" IL_002d: call ""void System.Console.Write(decimal)"" IL_0032: ret } "); } [Fact] public void AddressUnbox() { string source = @" using System; class Program { public struct S1 { public int x; public void Goo() { x = 123; } } public static S1 goo() { return new S1(); } static void Main() { goo().ToString(); Console.Write(goo().x); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0"); compilation.VerifyIL("Program.Main", @"{ // Code size 36 (0x24) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: call ""Program.S1 Program.goo()"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. ""Program.S1"" IL_000e: callvirt ""string object.ToString()"" IL_0013: pop IL_0014: call ""Program.S1 Program.goo()"" IL_0019: ldfld ""int Program.S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret } "); } [Fact] public void EqualsHashcode() { string source = @" using System; struct S1 { public int field; public override bool Equals(object obj) { return obj is S1 && field == ((S1)obj).field; } public override int GetHashCode() { return field; } public static bool operator ==(S1 value1, S1 value2) { return value1.field == value2.field; } public static bool operator !=(S1 value1, S1 value2) { return value1.field != value2.field; } } class Program { static void Main(string[] args) { } } "; var compilation = CompileAndVerify(source, expectedOutput: @""); compilation.VerifyIL("S1.Equals(object)", @" { // Code size 30 (0x1e) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S1"" IL_0006: brfalse.s IL_001c IL_0008: ldarg.0 IL_0009: ldfld ""int S1.field"" IL_000e: ldarg.1 IL_000f: unbox ""S1"" IL_0014: ldfld ""int S1.field"" IL_0019: ceq IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret } ").VerifyIL("S1.GetHashCode()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ret } ").VerifyIL("bool S1.op_Equality(S1, S1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ldarg.1 IL_0007: ldfld ""int S1.field"" IL_000c: ceq IL_000e: ret } ").VerifyIL("bool S1.op_Inequality(S1, S1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int S1.field"" IL_0006: ldarg.1 IL_0007: ldfld ""int S1.field"" IL_000c: ceq IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } "); } [Fact] public void EmitObjectGetTypeCallOnStruct() { string source = @" using System; class Program { public struct S1 { } static void Main() { Console.Write((new S1()).GetType()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+S1"); compilation.VerifyIL("Program.Main", @"{ // Code size 25 (0x19) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""Program.S1"" IL_0008: ldloc.0 IL_0009: box ""Program.S1"" IL_000e: call ""System.Type object.GetType()"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret } "); } [Fact] public void EmitInterfaceMethodOnStruct() { string source = @" using System; class Program { interface I { void M(); } struct S : I { public void M() { Console.WriteLine(""S::M""); } } static void Main(string[] args) { S s = new S(); s.M(); ((I)s).M(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"S::M S::M"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (Program.S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""Program.S"" IL_0008: ldloca.s V_0 IL_000a: call ""void Program.S.M()"" IL_000f: ldloc.0 IL_0010: box ""Program.S"" IL_0015: callvirt ""void Program.I.M()"" IL_001a: ret } "); } [Fact] public void ValueTypeWithGeneric() { string source = @" namespace NS { using System; using N2; namespace N2 { public interface IGoo<T> { void M(T t); } struct S<T, V> : IGoo<T> { public S(V v) { field = v; } public V field; public void M(T t) { Console.WriteLine(t); } } } public class Test { static S<N2, char>[] ary; class N1 { } class N2 : N1 { } static void Main() { IGoo<string> goo = new S<string, byte>(255); goo.M(""Abc""); Console.WriteLine(((S<string, byte>)goo).field); ary = new S<N2, char>[3]; ary[0] = ary[1] = ary[2] = new S<N2, char>('q'); Console.WriteLine(ary[1].field); } } } "; var compilation = CompileAndVerify(source, expectedOutput: @" Abc 255 q"); compilation.VerifyIL("NS.Test.Main", @"{ // Code size 120 (0x78) .maxstack 8 .locals init (NS.N2.S<NS.Test.N2, char> V_0) IL_0000: ldc.i4 0xff IL_0005: newobj ""NS.N2.S<string, byte>..ctor(byte)"" IL_000a: box ""NS.N2.S<string, byte>"" IL_000f: dup IL_0010: ldstr ""Abc"" IL_0015: callvirt ""void NS.N2.IGoo<string>.M(string)"" IL_001a: unbox ""NS.N2.S<string, byte>"" IL_001f: ldfld ""byte NS.N2.S<string, byte>.field"" IL_0024: call ""void System.Console.WriteLine(int)"" IL_0029: ldc.i4.3 IL_002a: newarr ""NS.N2.S<NS.Test.N2, char>"" IL_002f: stsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0034: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0039: ldc.i4.0 IL_003a: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_003f: ldc.i4.1 IL_0040: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0045: ldc.i4.2 IL_0046: ldc.i4.s 113 IL_0048: newobj ""NS.N2.S<NS.Test.N2, char>..ctor(char)"" IL_004d: dup IL_004e: stloc.0 IL_004f: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_0054: ldloc.0 IL_0055: dup IL_0056: stloc.0 IL_0057: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_005c: ldloc.0 IL_005d: stelem ""NS.N2.S<NS.Test.N2, char>"" IL_0062: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary"" IL_0067: ldc.i4.1 IL_0068: ldelema ""NS.N2.S<NS.Test.N2, char>"" IL_006d: ldfld ""char NS.N2.S<NS.Test.N2, char>.field"" IL_0072: call ""void System.Console.WriteLine(char)"" IL_0077: ret } "); } [WorkItem(540954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540954")] [Fact] public void StructInit() { var text = @" struct Struct { public static void Main() { Struct s = new Struct(); } } "; string expectedIL = @" { // Code size 10 (0xa) .maxstack 1 .locals init (Struct V_0) //s IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""Struct"" IL_0009: ret } "; CompileAndVerify(text, options: TestOptions.DebugExe).VerifyIL("Struct.Main()", expectedIL); } [WorkItem(541845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541845")] [Fact] public void ConstructEnum() { var text = @" using System; class A { enum E1 { AA } static void Main() { var v = new DayOfWeek(); Console.Write(v.ToString()); var e = new E1(); Console.WriteLine(e.ToString()); } } "; string expectedIL = @" { // Code size 41 (0x29) .maxstack 1 .locals init (System.DayOfWeek V_0, //v A.E1 V_1) //e IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: constrained. ""System.DayOfWeek"" IL_000a: callvirt ""string object.ToString()"" IL_000f: call ""void System.Console.Write(string)"" IL_0014: ldc.i4.0 IL_0015: stloc.1 IL_0016: ldloca.s V_1 IL_0018: constrained. ""A.E1"" IL_001e: callvirt ""string object.ToString()"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ret }"; CompileAndVerify(text, expectedOutput: "SundayAA").VerifyIL("A.Main()", expectedIL); } [WorkItem(541599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541599")] [Fact] public void TestStructWithStaticField01() { var source = @" using System; public struct S { public static int _verify = 123; static void Main() { Console.Write(_verify); } } "; CompileAndVerify(source, expectedOutput: @"123"); } [Fact, WorkItem(543088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543088")] public void UseStructLocal() { var text = @" using System; struct GetProperty { int i; GetProperty(int x) { i = x; } static void Main() { GetProperty t = new GetProperty(123); Console.Write(t.i); } } "; CompileAndVerify(text, expectedOutput: "123"); } [Fact] public void InplaceInit001() { string source = @" public class D { public struct Boo { public int I1; } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { v1 = default(Boo); DummyUse(v1); Boo v2 = default(Boo); DummyUse(v2); rArg = default(Boo); DummyUse(rArg); vArg = default(Boo); DummyUse(rArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 73 (0x49) .maxstack 1 .locals init (D.Boo V_0) IL_0000: ldsflda ""D.Boo D.v1"" IL_0005: initobj ""D.Boo"" IL_000b: ldsfld ""D.Boo D.v1"" IL_0010: call ""void D.DummyUse(D.Boo)"" IL_0015: ldloca.s V_0 IL_0017: initobj ""D.Boo"" IL_001d: ldloc.0 IL_001e: call ""void D.DummyUse(D.Boo)"" IL_0023: ldarg.0 IL_0024: initobj ""D.Boo"" IL_002a: ldarg.0 IL_002b: ldobj ""D.Boo"" IL_0030: call ""void D.DummyUse(D.Boo)"" IL_0035: ldarga.s V_1 IL_0037: initobj ""D.Boo"" IL_003d: ldarg.0 IL_003e: ldobj ""D.Boo"" IL_0043: call ""void D.DummyUse(D.Boo)"" IL_0048: ret } "); } [Fact] public void InplaceInit002() { string source = @" public class D { public struct Boo { public int I1; } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { try { v1 = default(Boo); DummyUse(v1); Boo v2 = default(Boo); DummyUse(v2); rArg = default(Boo); DummyUse(rArg); vArg = default(Boo); DummyUse(rArg); } catch (System.Exception) { rArg = default(Boo); DummyUse(rArg); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 96 (0x60) .maxstack 1 .locals init (D.Boo V_0) .try { IL_0000: ldsflda ""D.Boo D.v1"" IL_0005: initobj ""D.Boo"" IL_000b: ldsfld ""D.Boo D.v1"" IL_0010: call ""void D.DummyUse(D.Boo)"" IL_0015: ldloca.s V_0 IL_0017: initobj ""D.Boo"" IL_001d: ldloc.0 IL_001e: call ""void D.DummyUse(D.Boo)"" IL_0023: ldarg.0 IL_0024: initobj ""D.Boo"" IL_002a: ldarg.0 IL_002b: ldobj ""D.Boo"" IL_0030: call ""void D.DummyUse(D.Boo)"" IL_0035: ldarga.s V_1 IL_0037: initobj ""D.Boo"" IL_003d: ldarg.0 IL_003e: ldobj ""D.Boo"" IL_0043: call ""void D.DummyUse(D.Boo)"" IL_0048: leave.s IL_005f } catch System.Exception { IL_004a: pop IL_004b: ldarg.0 IL_004c: initobj ""D.Boo"" IL_0052: ldarg.0 IL_0053: ldobj ""D.Boo"" IL_0058: call ""void D.DummyUse(D.Boo)"" IL_005d: leave.s IL_005f } IL_005f: ret } "); } [Fact] public void InplaceCtor001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { //try //{ v1 = new Boo(42); DummyUse(v1); Boo v2 = new Boo(42); DummyUse(v2); rArg = new Boo(42); DummyUse(rArg); vArg = new Boo(42); DummyUse(rArg); //} //catch (System.Exception) // // rArg = new Boo(42); // DummyUse(rArg); //} } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 79 (0x4f) .maxstack 2 IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: stsfld ""D.Boo D.v1"" IL_000c: ldsfld ""D.Boo D.v1"" IL_0011: call ""void D.DummyUse(D.Boo)"" IL_0016: ldc.i4.s 42 IL_0018: newobj ""D.Boo..ctor(int)"" IL_001d: call ""void D.DummyUse(D.Boo)"" IL_0022: ldarg.0 IL_0023: ldc.i4.s 42 IL_0025: newobj ""D.Boo..ctor(int)"" IL_002a: stobj ""D.Boo"" IL_002f: ldarg.0 IL_0030: ldobj ""D.Boo"" IL_0035: call ""void D.DummyUse(D.Boo)"" IL_003a: ldarga.s V_1 IL_003c: ldc.i4.s 42 IL_003e: call ""D.Boo..ctor(int)"" IL_0043: ldarg.0 IL_0044: ldobj ""D.Boo"" IL_0049: call ""void D.DummyUse(D.Boo)"" IL_004e: ret } "); } [Fact] public void InplaceCtor002() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { Boo v3; try{ Boo v3a; try { v1 = new Boo(42); DummyUse(v1); Boo v2 = new Boo(43); DummyUse(v2); v3 = new Boo(44); v3.ToString(); // should be a call, since v4 is defined in the same try scope Boo v4 = new Boo(45); v4.ToString(); rArg = new Boo(46); DummyUse(rArg); vArg = new Boo(47); DummyUse(rArg); } catch (System.Exception) { v3 = new Boo(44); v3.ToString(); // should be a call, since v3a is defined in the same try scope v3a = new Boo(44); v3a.ToString(); // should be a call, since v4 is defined in the same try scope Boo v4 = new Boo(45); v4.ToString(); rArg = new Boo(48); DummyUse(rArg); } } finally { } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 222 (0xde) .maxstack 2 .locals init (D.Boo V_0, //v3 D.Boo V_1, //v3a D.Boo V_2, //v4 D.Boo V_3) //v4 .try { IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: stsfld ""D.Boo D.v1"" IL_000c: ldsfld ""D.Boo D.v1"" IL_0011: call ""void D.DummyUse(D.Boo)"" IL_0016: ldc.i4.s 43 IL_0018: newobj ""D.Boo..ctor(int)"" IL_001d: call ""void D.DummyUse(D.Boo)"" IL_0022: ldc.i4.s 44 IL_0024: newobj ""D.Boo..ctor(int)"" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""D.Boo"" IL_0032: callvirt ""string object.ToString()"" IL_0037: pop IL_0038: ldloca.s V_2 IL_003a: ldc.i4.s 45 IL_003c: call ""D.Boo..ctor(int)"" IL_0041: ldloca.s V_2 IL_0043: constrained. ""D.Boo"" IL_0049: callvirt ""string object.ToString()"" IL_004e: pop IL_004f: ldarg.0 IL_0050: ldc.i4.s 46 IL_0052: newobj ""D.Boo..ctor(int)"" IL_0057: stobj ""D.Boo"" IL_005c: ldarg.0 IL_005d: ldobj ""D.Boo"" IL_0062: call ""void D.DummyUse(D.Boo)"" IL_0067: ldc.i4.s 47 IL_0069: newobj ""D.Boo..ctor(int)"" IL_006e: starg.s V_1 IL_0070: ldarg.0 IL_0071: ldobj ""D.Boo"" IL_0076: call ""void D.DummyUse(D.Boo)"" IL_007b: leave.s IL_00dd } catch System.Exception { IL_007d: pop IL_007e: ldloca.s V_0 IL_0080: ldc.i4.s 44 IL_0082: call ""D.Boo..ctor(int)"" IL_0087: ldloca.s V_0 IL_0089: constrained. ""D.Boo"" IL_008f: callvirt ""string object.ToString()"" IL_0094: pop IL_0095: ldloca.s V_1 IL_0097: ldc.i4.s 44 IL_0099: call ""D.Boo..ctor(int)"" IL_009e: ldloca.s V_1 IL_00a0: constrained. ""D.Boo"" IL_00a6: callvirt ""string object.ToString()"" IL_00ab: pop IL_00ac: ldloca.s V_3 IL_00ae: ldc.i4.s 45 IL_00b0: call ""D.Boo..ctor(int)"" IL_00b5: ldloca.s V_3 IL_00b7: constrained. ""D.Boo"" IL_00bd: callvirt ""string object.ToString()"" IL_00c2: pop IL_00c3: ldarg.0 IL_00c4: ldc.i4.s 48 IL_00c6: newobj ""D.Boo..ctor(int)"" IL_00cb: stobj ""D.Boo"" IL_00d0: ldarg.0 IL_00d1: ldobj ""D.Boo"" IL_00d6: call ""void D.DummyUse(D.Boo)"" IL_00db: leave.s IL_00dd } IL_00dd: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [Fact] public void InplaceCtor003() { string source = @" public class D { public struct Boo { public int I1; public Boo(ref int i1) { this.I1 = 1; this.I1 += i1; } public Boo(ref Boo b1) { this.I1 = 1; this.I1 += b1.I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); a1 = new Boo(ref a1); System.Console.Write(a1.I1); v1 = new Boo(ref v1); System.Console.Write(v1.I1); a1 = default(Boo); v1 = default(Boo); a1 = new Boo(ref a1.I1); System.Console.Write(a1.I1); v1 = new Boo(ref v1.I1); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "1111"); compilation.VerifyIL("D.Main", @" { // Code size 136 (0x88) .maxstack 1 .locals init (D.Boo V_0) //a1 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldloca.s V_0 IL_000a: newobj ""D.Boo..ctor(ref D.Boo)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: ldfld ""int D.Boo.I1"" IL_0016: call ""void System.Console.Write(int)"" IL_001b: ldsflda ""D.Boo D.v1"" IL_0020: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0025: stsfld ""D.Boo D.v1"" IL_002a: ldsflda ""D.Boo D.v1"" IL_002f: ldfld ""int D.Boo.I1"" IL_0034: call ""void System.Console.Write(int)"" IL_0039: ldloca.s V_0 IL_003b: initobj ""D.Boo"" IL_0041: ldsflda ""D.Boo D.v1"" IL_0046: initobj ""D.Boo"" IL_004c: ldloca.s V_0 IL_004e: ldflda ""int D.Boo.I1"" IL_0053: newobj ""D.Boo..ctor(ref int)"" IL_0058: stloc.0 IL_0059: ldloc.0 IL_005a: ldfld ""int D.Boo.I1"" IL_005f: call ""void System.Console.Write(int)"" IL_0064: ldsflda ""D.Boo D.v1"" IL_0069: ldflda ""int D.Boo.I1"" IL_006e: newobj ""D.Boo..ctor(ref int)"" IL_0073: stsfld ""D.Boo D.v1"" IL_0078: ldsflda ""D.Boo D.v1"" IL_007d: ldfld ""int D.Boo.I1"" IL_0082: call ""void System.Console.Write(int)"" IL_0087: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [Fact] public void InplaceCtor004() { string source = @" public class D { public struct Boo { public int I1; public Boo(ref int i1) { this.I1 = 1; this.I1 += i1; } public Boo(ref Boo b1) { this.I1 = 1; this.I1 += b1.I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); ref var r1 = ref a1; a1 = new Boo(ref r1); System.Console.Write(a1.I1); ref var r2 = ref v1; v1 = new Boo(ref r2); System.Console.Write(v1.I1); a1 = default(Boo); v1 = default(Boo); ref var r3 = ref a1.I1; a1 = new Boo(ref r3); System.Console.Write(a1.I1); ref var r4 = ref v1.I1; v1 = new Boo(ref r4); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "1111"); compilation.VerifyIL("D.Main", @" { // Code size 146 (0x92) .maxstack 1 .locals init (D.Boo V_0, //a1 D.Boo& V_1, //r1 D.Boo& V_2, //r2 int& V_3, //r3 int& V_4) //r4 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldloca.s V_0 IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldfld ""int D.Boo.I1"" IL_0018: call ""void System.Console.Write(int)"" IL_001d: ldsflda ""D.Boo D.v1"" IL_0022: stloc.2 IL_0023: ldloc.2 IL_0024: newobj ""D.Boo..ctor(ref D.Boo)"" IL_0029: stsfld ""D.Boo D.v1"" IL_002e: ldsflda ""D.Boo D.v1"" IL_0033: ldfld ""int D.Boo.I1"" IL_0038: call ""void System.Console.Write(int)"" IL_003d: ldloca.s V_0 IL_003f: initobj ""D.Boo"" IL_0045: ldsflda ""D.Boo D.v1"" IL_004a: initobj ""D.Boo"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""int D.Boo.I1"" IL_0057: stloc.3 IL_0058: ldloc.3 IL_0059: newobj ""D.Boo..ctor(ref int)"" IL_005e: stloc.0 IL_005f: ldloc.0 IL_0060: ldfld ""int D.Boo.I1"" IL_0065: call ""void System.Console.Write(int)"" IL_006a: ldsflda ""D.Boo D.v1"" IL_006f: ldflda ""int D.Boo.I1"" IL_0074: stloc.s V_4 IL_0076: ldloc.s V_4 IL_0078: newobj ""D.Boo..ctor(ref int)"" IL_007d: stsfld ""D.Boo D.v1"" IL_0082: ldsflda ""D.Boo D.v1"" IL_0087: ldfld ""int D.Boo.I1"" IL_008c: call ""void System.Console.Write(int)"" IL_0091: ret } "); } [WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void InplaceCtor005() { string source = @" using System; public class D { public struct Boo { public int I1; public Boo(int x, __arglist) { this.I1 = 1; this.I1 += __refvalue(new ArgIterator(__arglist).GetNextArg(), Boo).I1; } } public static Boo v1; public static void Main() { Boo a1 = default(Boo); a1 = new Boo(1, __arglist(ref a1)); System.Console.Write(a1.I1); v1 = new Boo(1, __arglist(ref v1)); System.Console.Write(v1.I1); } } "; var compilation = CompileAndVerify(source, expectedOutput: "11"); compilation.VerifyIL("D.Main", @" { // Code size 60 (0x3c) .maxstack 2 .locals init (D.Boo V_0) //a1 IL_0000: ldloca.s V_0 IL_0002: initobj ""D.Boo"" IL_0008: ldc.i4.1 IL_0009: ldloca.s V_0 IL_000b: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldfld ""int D.Boo.I1"" IL_0017: call ""void System.Console.Write(int)"" IL_001c: ldc.i4.1 IL_001d: ldsflda ""D.Boo D.v1"" IL_0022: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)"" IL_0027: stsfld ""D.Boo D.v1"" IL_002c: ldsflda ""D.Boo D.v1"" IL_0031: ldfld ""int D.Boo.I1"" IL_0036: call ""void System.Console.Write(int)"" IL_003b: ret } "); } [Fact] public void InitUsed001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void DummyUse1(ref Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { DummyUse(v1 = default(Boo)); DummyUse(v1); Boo v2; DummyUse(v2 = default(Boo)); DummyUse(v2); // TODO: no need for a temp Boo v2a; DummyUse(v2a = default(Boo)); DummyUse1(ref v2a); DummyUse(rArg = default(Boo)); DummyUse(rArg); // TODO: no need for a temp DummyUse(vArg = default(Boo)); DummyUse(vArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 126 (0x7e) .maxstack 3 .locals init (D.Boo V_0, //v2a D.Boo V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""D.Boo"" IL_0008: ldloc.1 IL_0009: dup IL_000a: stsfld ""D.Boo D.v1"" IL_000f: call ""void D.DummyUse(D.Boo)"" IL_0014: ldsfld ""D.Boo D.v1"" IL_0019: call ""void D.DummyUse(D.Boo)"" IL_001e: ldloca.s V_1 IL_0020: initobj ""D.Boo"" IL_0026: ldloc.1 IL_0027: dup IL_0028: call ""void D.DummyUse(D.Boo)"" IL_002d: call ""void D.DummyUse(D.Boo)"" IL_0032: ldloca.s V_0 IL_0034: initobj ""D.Boo"" IL_003a: ldloc.0 IL_003b: call ""void D.DummyUse(D.Boo)"" IL_0040: ldloca.s V_0 IL_0042: call ""void D.DummyUse1(ref D.Boo)"" IL_0047: ldarg.0 IL_0048: ldloca.s V_1 IL_004a: initobj ""D.Boo"" IL_0050: ldloc.1 IL_0051: dup IL_0052: stloc.1 IL_0053: stobj ""D.Boo"" IL_0058: ldloc.1 IL_0059: call ""void D.DummyUse(D.Boo)"" IL_005e: ldarg.0 IL_005f: ldobj ""D.Boo"" IL_0064: call ""void D.DummyUse(D.Boo)"" IL_0069: ldarga.s V_1 IL_006b: initobj ""D.Boo"" IL_0071: ldarg.1 IL_0072: call ""void D.DummyUse(D.Boo)"" IL_0077: ldarg.1 IL_0078: call ""void D.DummyUse(D.Boo)"" IL_007d: ret } "); } [Fact] public void CtorUsed001() { string source = @" public class D { public struct Boo { public int I1; public Boo(int i1) { this.I1 = i1; } } public static Boo v1; public static void DummyUse(Boo arg) { } public static void DummyUse1(ref Boo arg) { } public static void Main() { Boo a1 = default(Boo); Boo a2 = default(Boo); TestInit(out a1, a2); } private static void TestInit(out Boo rArg, Boo vArg) { DummyUse(v1 = new Boo(42)); DummyUse(v1); Boo v2; DummyUse(v2 = new Boo(42)); DummyUse(v2); Boo v2a; DummyUse(v2a = new Boo(42)); DummyUse1(ref v2a); DummyUse(rArg = new Boo(42)); DummyUse(rArg); DummyUse(vArg = new Boo(42)); DummyUse(vArg); } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); compilation.VerifyIL("D.TestInit", @" { // Code size 122 (0x7a) .maxstack 3 .locals init (D.Boo V_0, //v2a D.Boo V_1) IL_0000: ldc.i4.s 42 IL_0002: newobj ""D.Boo..ctor(int)"" IL_0007: dup IL_0008: stsfld ""D.Boo D.v1"" IL_000d: call ""void D.DummyUse(D.Boo)"" IL_0012: ldsfld ""D.Boo D.v1"" IL_0017: call ""void D.DummyUse(D.Boo)"" IL_001c: ldc.i4.s 42 IL_001e: newobj ""D.Boo..ctor(int)"" IL_0023: dup IL_0024: call ""void D.DummyUse(D.Boo)"" IL_0029: call ""void D.DummyUse(D.Boo)"" IL_002e: ldloca.s V_0 IL_0030: ldc.i4.s 42 IL_0032: call ""D.Boo..ctor(int)"" IL_0037: ldloc.0 IL_0038: call ""void D.DummyUse(D.Boo)"" IL_003d: ldloca.s V_0 IL_003f: call ""void D.DummyUse1(ref D.Boo)"" IL_0044: ldarg.0 IL_0045: ldc.i4.s 42 IL_0047: newobj ""D.Boo..ctor(int)"" IL_004c: dup IL_004d: stloc.1 IL_004e: stobj ""D.Boo"" IL_0053: ldloc.1 IL_0054: call ""void D.DummyUse(D.Boo)"" IL_0059: ldarg.0 IL_005a: ldobj ""D.Boo"" IL_005f: call ""void D.DummyUse(D.Boo)"" IL_0064: ldarga.s V_1 IL_0066: ldc.i4.s 42 IL_0068: call ""D.Boo..ctor(int)"" IL_006d: ldarg.1 IL_006e: call ""void D.DummyUse(D.Boo)"" IL_0073: ldarg.1 IL_0074: call ""void D.DummyUse(D.Boo)"" IL_0079: ret } "); } [Fact] public void InheritedCallOnReadOnly() { string source = @" class Program { static void Main() { var obj = new C1(); System.Console.WriteLine(obj.field.ToString()); } } class C1 { public readonly S1 field; } struct S1 { } "; var compilation = CompileAndVerify(source, expectedOutput: "S1", verify: Verification.Skipped); compilation.VerifyIL("Program.Main", @" { // Code size 27 (0x1b) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ldflda ""S1 C1.field"" IL_000a: constrained. ""S1"" IL_0010: callvirt ""string object.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ret } "); compilation = CompileAndVerify(source, expectedOutput: "S1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); compilation.VerifyIL("Program.Main", @" { // Code size 30 (0x1e) .maxstack 1 .locals init (S1 V_0) IL_0000: newobj ""C1..ctor()"" IL_0005: ldfld ""S1 C1.field"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: constrained. ""S1"" IL_0013: callvirt ""string object.ToString()"" IL_0018: call ""void System.Console.WriteLine(string)"" IL_001d: ret } "); } [Fact] [WorkItem(27049, "https://github.com/dotnet/roslyn/issues/27049")] public void BoxingRefStructForBaseCall() { CreateCompilation(@" ref struct S { public override bool Equals(object obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); public override string ToString() => base.ToString(); }").VerifyDiagnostics( // (4,48): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override bool Equals(object obj) => base.Equals(obj); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(4, 48), // (6,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override int GetHashCode() => base.GetHashCode(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(6, 42), // (8,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType' // public override string ToString() => base.ToString(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(8, 42)); } #endregion #region "Enum" [Fact] public void TestEnum() { string source = @"enum E { A, B } class C { static void Main() { E e = E.A; e = e + 1; } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("C.Main", @"{ // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: pop IL_0002: ret } "); } [Fact] public void BoxEnum() { string source = @"enum E { A, B } class C { static void Main() { E e = E.B; object o = e; e = (E)o; System.Console.Write(e); } } "; var compilation = CompileAndVerify(source, expectedOutput: "B"); compilation.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""E"" IL_0006: unbox.any ""E"" IL_000b: box ""E"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ret } "); } [Fact] public void MBRO_StructField() { string source = @" using System; class Program { static void Main(string[] args) { var v = new cls1(); v.Test(); } } struct S1 { public Guid g; } class cls1 : MarshalByRefObject { public Guid g1; public S1 s; public void Test() { g1 = new Guid(); TestRef(ref g1); g1 = new Guid(g1.ToString()); System.Console.WriteLine(g1); System.Console.WriteLine(s.g.ToString()); var other = new cls1(); other.g1 = new Guid(); System.Console.WriteLine(other.g1); TestRef(ref other.g1); other.g1 = new Guid(other.g1.ToString()); System.Console.WriteLine(other.g1); System.Console.WriteLine(other.s.g.ToString()); var gg = other.s.g; System.Console.WriteLine(gg); } public void TestRef(ref Guid arg) { arg = new Guid(""ca761232ed4211cebacd00aa0057b223""); } } "; var compilation = CompileAndVerify(source, expectedOutput: @"ca761232-ed42-11ce-bacd-00aa0057b223 00000000-0000-0000-0000-000000000000 00000000-0000-0000-0000-000000000000 ca761232-ed42-11ce-bacd-00aa0057b223 00000000-0000-0000-0000-000000000000 00000000-0000-0000-0000-000000000000"); compilation.VerifyIL("cls1.Test", @" { // Code size 237 (0xed) .maxstack 2 .locals init (cls1 V_0, //other System.Guid V_1) IL_0000: ldarg.0 IL_0001: ldflda ""System.Guid cls1.g1"" IL_0006: initobj ""System.Guid"" IL_000c: ldarg.0 IL_000d: ldarg.0 IL_000e: ldflda ""System.Guid cls1.g1"" IL_0013: call ""void cls1.TestRef(ref System.Guid)"" IL_0018: ldarg.0 IL_0019: ldarg.0 IL_001a: ldflda ""System.Guid cls1.g1"" IL_001f: constrained. ""System.Guid"" IL_0025: callvirt ""string object.ToString()"" IL_002a: newobj ""System.Guid..ctor(string)"" IL_002f: stfld ""System.Guid cls1.g1"" IL_0034: ldarg.0 IL_0035: ldfld ""System.Guid cls1.g1"" IL_003a: box ""System.Guid"" IL_003f: call ""void System.Console.WriteLine(object)"" IL_0044: ldarg.0 IL_0045: ldflda ""S1 cls1.s"" IL_004a: ldflda ""System.Guid S1.g"" IL_004f: constrained. ""System.Guid"" IL_0055: callvirt ""string object.ToString()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: newobj ""cls1..ctor()"" IL_0064: stloc.0 IL_0065: ldloc.0 IL_0066: ldloca.s V_1 IL_0068: initobj ""System.Guid"" IL_006e: ldloc.1 IL_006f: stfld ""System.Guid cls1.g1"" IL_0074: ldloc.0 IL_0075: ldfld ""System.Guid cls1.g1"" IL_007a: box ""System.Guid"" IL_007f: call ""void System.Console.WriteLine(object)"" IL_0084: ldarg.0 IL_0085: ldloc.0 IL_0086: ldflda ""System.Guid cls1.g1"" IL_008b: call ""void cls1.TestRef(ref System.Guid)"" IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldflda ""System.Guid cls1.g1"" IL_0097: constrained. ""System.Guid"" IL_009d: callvirt ""string object.ToString()"" IL_00a2: newobj ""System.Guid..ctor(string)"" IL_00a7: stfld ""System.Guid cls1.g1"" IL_00ac: ldloc.0 IL_00ad: ldfld ""System.Guid cls1.g1"" IL_00b2: box ""System.Guid"" IL_00b7: call ""void System.Console.WriteLine(object)"" IL_00bc: ldloc.0 IL_00bd: ldflda ""S1 cls1.s"" IL_00c2: ldflda ""System.Guid S1.g"" IL_00c7: constrained. ""System.Guid"" IL_00cd: callvirt ""string object.ToString()"" IL_00d2: call ""void System.Console.WriteLine(string)"" IL_00d7: ldloc.0 IL_00d8: ldfld ""S1 cls1.s"" IL_00dd: ldfld ""System.Guid S1.g"" IL_00e2: box ""System.Guid"" IL_00e7: call ""void System.Console.WriteLine(object)"" IL_00ec: ret } "); } [Fact] public void InitTemp001() { string source = @" using System; struct S { int x; static void Main() { Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.x"" IL_0010: ldloca.s V_0 IL_0012: ldloca.s V_1 IL_0014: initobj ""S"" IL_001a: ldloca.s V_1 IL_001c: ldc.i4.1 IL_001d: stfld ""int S.x"" IL_0022: ldloc.1 IL_0023: box ""S"" IL_0028: constrained. ""S"" IL_002e: callvirt ""bool object.Equals(object)"" IL_0033: call ""void System.Console.WriteLine(bool)"" IL_0038: ret } "); } [Fact] public void InitTemp001a() { string source = @" using System; struct S1 { public int x; } struct S { public S1 x; static void Main() { Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 94 (0x5e) .maxstack 4 .locals init (S V_0, S1 V_1, S V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: initobj ""S1"" IL_0012: ldloca.s V_1 IL_0014: ldc.i4.0 IL_0015: stfld ""int S1.x"" IL_001a: ldloc.1 IL_001b: stfld ""S1 S.x"" IL_0020: ldloca.s V_0 IL_0022: ldflda ""S1 S.x"" IL_0027: ldloca.s V_2 IL_0029: initobj ""S"" IL_002f: ldloca.s V_2 IL_0031: ldloca.s V_1 IL_0033: initobj ""S1"" IL_0039: ldloca.s V_1 IL_003b: ldc.i4.1 IL_003c: stfld ""int S1.x"" IL_0041: ldloc.1 IL_0042: stfld ""S1 S.x"" IL_0047: ldloc.2 IL_0048: box ""S"" IL_004d: constrained. ""S1"" IL_0053: callvirt ""bool object.Equals(object)"" IL_0058: call ""void System.Console.WriteLine(bool)"" IL_005d: ret } "); } [Fact] public void InitTemp001b() { string source = @" using System; class S1 { public int x; } struct S { public S1 x; static void Main() { Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} })); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 77 (0x4d) .maxstack 5 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: newobj ""S1..ctor()"" IL_000f: dup IL_0010: ldc.i4.0 IL_0011: stfld ""int S1.x"" IL_0016: stfld ""S1 S.x"" IL_001b: ldloc.0 IL_001c: ldfld ""S1 S.x"" IL_0021: ldloca.s V_0 IL_0023: initobj ""S"" IL_0029: ldloca.s V_0 IL_002b: newobj ""S1..ctor()"" IL_0030: dup IL_0031: ldc.i4.1 IL_0032: stfld ""int S1.x"" IL_0037: stfld ""S1 S.x"" IL_003c: ldloc.0 IL_003d: box ""S"" IL_0042: callvirt ""bool object.Equals(object)"" IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ret } "); } [Fact] public void InitTemp002() { string source = @" using System; struct S { int x; static void Main() { Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }).Equals( new S { x = 1 }.Equals(new S { x = 1 }))); } } "; var compilation = CompileAndVerify(source, expectedOutput: "False"); compilation.VerifyIL("S.Main", @" { // Code size 116 (0x74) .maxstack 4 .locals init (S V_0, S V_1, bool V_2, S V_3) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.x"" IL_0010: ldloca.s V_0 IL_0012: ldloca.s V_1 IL_0014: initobj ""S"" IL_001a: ldloca.s V_1 IL_001c: ldc.i4.1 IL_001d: stfld ""int S.x"" IL_0022: ldloc.1 IL_0023: box ""S"" IL_0028: constrained. ""S"" IL_002e: callvirt ""bool object.Equals(object)"" IL_0033: stloc.2 IL_0034: ldloca.s V_2 IL_0036: ldloca.s V_1 IL_0038: initobj ""S"" IL_003e: ldloca.s V_1 IL_0040: ldc.i4.1 IL_0041: stfld ""int S.x"" IL_0046: ldloca.s V_1 IL_0048: ldloca.s V_3 IL_004a: initobj ""S"" IL_0050: ldloca.s V_3 IL_0052: ldc.i4.1 IL_0053: stfld ""int S.x"" IL_0058: ldloc.3 IL_0059: box ""S"" IL_005e: constrained. ""S"" IL_0064: callvirt ""bool object.Equals(object)"" IL_0069: call ""bool bool.Equals(bool)"" IL_006e: call ""void System.Console.WriteLine(bool)"" IL_0073: ret } "); } [Fact] public void InitTemp003() { string source = @" using System; readonly struct S { readonly int x; public S(int x) { this.x = x; } static void Main() { // named argument reordering introduces a sequence with temps // and we cannot know whether RefMethod returns a ref to a sequence local // so we must assume that it can, and therefore must keep all the sequence the locals in use // for the duration of the most-encompassing expression. Console.WriteLine(RefMethod(arg2: I(5), arg1: I(3)).GreaterThan( RefMethod(arg2: I(0), arg1: I(0)))); } public static ref readonly S RefMethod(in S arg1, in S arg2) { return ref arg2; } public bool GreaterThan(in S arg) { return this.x > arg.x; } public static S I(int arg) { return new S(arg); } } "; var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: "True"); compilation.VerifyIL("S.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, S V_1, S V_2, S V_3) IL_0000: ldc.i4.5 IL_0001: call ""S S.I(int)"" IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: call ""S S.I(int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldloca.s V_0 IL_0012: call ""ref readonly S S.RefMethod(in S, in S)"" IL_0017: ldc.i4.0 IL_0018: call ""S S.I(int)"" IL_001d: stloc.2 IL_001e: ldc.i4.0 IL_001f: call ""S S.I(int)"" IL_0024: stloc.3 IL_0025: ldloca.s V_3 IL_0027: ldloca.s V_2 IL_0029: call ""ref readonly S S.RefMethod(in S, in S)"" IL_002e: call ""bool S.GreaterThan(in S)"" IL_0033: call ""void System.Console.WriteLine(bool)"" IL_0038: ret } "); } [Fact] public void InitTemp004() { string source = @" using System; readonly struct S { public readonly int x; public S(int x) { this.x = x; } static void Main() { System.Console.Write(TestRO().x); System.Console.WriteLine(); System.Console.Write(Test().x); } static ref readonly S TestRO() { try { // both args are refs return ref RefMethodRO(arg2: I(5), arg1: I(3)); } finally { // first arg is a value!! RefMethodRO(arg2: I_Val(5), arg1: I(3)); } } public static ref readonly S RefMethodRO(in S arg1, in S arg2) { System.Console.Write(arg2.x); return ref arg2; } // similar as above, but with regular (not readonly) refs for comparison static ref S Test() { try { return ref RefMethod(arg2: ref I(5), arg1: ref I(3)); } finally { var temp = I(5); RefMethod(arg2: ref temp, arg1: ref I(3)); } } public static ref S RefMethod(ref S arg1, ref S arg2) { System.Console.Write(arg2.x); return ref arg2; } private static S[] arr = new S[] { new S() }; public static ref S I(int arg) { arr[0] = new S(arg); return ref arr[0]; } public static S I_Val(int arg) { arr[0] = new S(arg); return arr[0]; } } "; var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: @"353 353"); compilation.VerifyIL("S.TestRO", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (S& V_0, S& V_1, S V_2) .try { IL_0000: ldc.i4.5 IL_0001: call ""ref S S.I(int)"" IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: call ""ref S S.I(int)"" IL_000d: ldloc.0 IL_000e: call ""ref readonly S S.RefMethodRO(in S, in S)"" IL_0013: stloc.1 IL_0014: leave.s IL_002c } finally { IL_0016: ldc.i4.5 IL_0017: call ""S S.I_Val(int)"" IL_001c: stloc.2 IL_001d: ldc.i4.3 IL_001e: call ""ref S S.I(int)"" IL_0023: ldloca.s V_2 IL_0025: call ""ref readonly S S.RefMethodRO(in S, in S)"" IL_002a: pop IL_002b: endfinally } IL_002c: ldloc.1 IL_002d: ret } "); } [WorkItem(842477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842477")] [Fact] public void DecimalConst() { string source = @" #pragma warning disable 458, 169, 414 using System; public class NullableTest { static decimal? NULL = null; public static void EqualEqual() { Test.Eval((decimal?)1m == null, false); Test.Eval((decimal?)1m == NULL, false); Test.Eval((decimal?)0 == NULL, false); } } public class Test { public static void Eval(object obj1, object obj2) { } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("NullableTest.EqualEqual", @" { // Code size 112 (0x70) .maxstack 2 .locals init (decimal? V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: ldc.i4.0 IL_0007: box ""bool"" IL_000c: call ""void Test.Eval(object, object)"" IL_0011: ldsfld ""decimal decimal.One"" IL_0016: ldsfld ""decimal? NullableTest.NULL"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: call ""decimal decimal?.GetValueOrDefault()"" IL_0023: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0028: ldloca.s V_0 IL_002a: call ""bool decimal?.HasValue.get"" IL_002f: and IL_0030: box ""bool"" IL_0035: ldc.i4.0 IL_0036: box ""bool"" IL_003b: call ""void Test.Eval(object, object)"" IL_0040: ldsfld ""decimal decimal.Zero"" IL_0045: ldsfld ""decimal? NullableTest.NULL"" IL_004a: stloc.0 IL_004b: ldloca.s V_0 IL_004d: call ""decimal decimal?.GetValueOrDefault()"" IL_0052: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0057: ldloca.s V_0 IL_0059: call ""bool decimal?.HasValue.get"" IL_005e: and IL_005f: box ""bool"" IL_0064: ldc.i4.0 IL_0065: box ""bool"" IL_006a: call ""void Test.Eval(object, object)"" IL_006f: ret } "); } [Fact] public void FieldLoad001() { string source = @" using System; struct Point { public int x; public int y; } class Rectangle { public Point topLeft; public Point bottomRight; } struct C1 { public C1(int i) { r = new Rectangle(); } public Rectangle r; } class Program { static object p = new C1(1); static void Main(string[] args) { System.Console.WriteLine(((C1)p).r.topLeft.x); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @" { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldsfld ""object Program.p"" IL_0005: unbox ""C1"" IL_000a: ldfld ""Rectangle C1.r"" IL_000f: ldflda ""Point Rectangle.topLeft"" IL_0014: ldfld ""int Point.x"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ret } "); } #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/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems
<?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>Microsoft.CodeAnalysis.CSharp.Analyzers</Import_RootNamespace> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)CSharpAnalyzersResources.resx" GenerateSource="true" Link="CSharpAnalyzersResources.resx" /> <None Include="$(MSBuildThisFileDirectory)CSharpAnalyzersResources.resx"> <SubType>Designer</SubType> </None> </ItemGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddBraces\CSharpAddBracesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddRequiredParentheses\CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertNamespaceAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertTypeofToNameof\CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConsecutiveBracePlacement\ConsecutiveBracePlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConsecutiveStatementPlacement\CSharpConsecutiveStatementPlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConstructorInitializerPlacement\ConstructorInitializerPlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\MultipleBlankLines\CSharpMultipleBlankLinesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MatchFolderAndNamespace\CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveRedundantEquality\CSharpRemoveRedundantEqualityDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryDiscardDesignation\CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessarySuppressions\CSharpRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessarySuppressions\CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryParentheses\CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddRequiredParentheses\CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveConfusingSuppression\CSharpRemoveConfusingSuppressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionConstants.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FileHeaders\CSharpFileHeaderDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FileHeaders\CSharpFileHeaderHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)InlineDeclaration\CSharpInlineDeclarationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)InvokeDelegateWithConditionalAccess\InvokeDelegateWithConditionalAccessAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeLocalFunctionStatic\MakeLocalFunctionStaticDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeLocalFunctionStatic\MakeLocalFunctionStaticHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeStructFieldsWritable\CSharpMakeStructFieldsWritableDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MisplacedUsingDirectives\MisplacedUsingDirectivesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyle\CSharpNamingStyleDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)OrderModifiers\CSharpOrderModifiersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)OrderModifiers\CSharpOrderModifiersHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)PopulateSwitch\CSharpPopulateSwitchExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)PopulateSwitch\CSharpPopulateSwitchStatementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnreachableCode\CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnreachableCode\RemoveUnreachableCodeHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyBooleanExpression\CSharpSimplifyConditionalDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyInterpolation\CSharpSimplifyInterpolationHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyInterpolation\CSharpSimplifyInterpolationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyLinqExpression\CSharpSimplifyLinqExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseAutoProperty\CSharpUseAutoPropertyAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCoalesceExpression\CSharpUseCoalesceExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCoalesceExpression\CSharpUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\CSharpUseCompoundAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\Utilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseConditionalExpression\CSharpUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseConditionalExpression\CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseDeconstruction\CSharpUseDeconstructionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseDefaultLiteral\CSharpUseDefaultLiteralDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForAccessorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForConstructorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForConversionOperatorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForIndexersHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForLocalFunctionHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForMethodsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForOperatorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForPropertiesHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyHelper`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\UseExpressionBodyDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)QualifyMemberAccess\CSharpQualifyMemberAccessDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryCast\CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryImports\CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryParentheses\CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnusedMembers\CSharpRemoveUnusedMembersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnusedParametersAndValues\CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCollectionInitializer\CSharpUseCollectionInitializerDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitObjectCreation\CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpTypeStyleDiagnosticAnalyzerBase.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpUseExplicitTypeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpUseImplicitTypeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseIndexOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseIndexOperatorDiagnosticAnalyzer.InfoCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\Helpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\MemberInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseInferredMemberName\CSharpUseInferredMemberNameDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseLocalFunction\CSharpUseLocalFunctionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\CSharpUseNullPropagationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\CSharpUseObjectInitializerDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\AnalyzedPattern.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\CSharpUsePatternCombinatorsAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpAsAndNullCheckDiagnosticAnalyzer.Analyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpAsAndNullCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpIsAndCastCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpUseNotPatternDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseSimpleUsingStatement\UseSimpleUsingStatementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\CSharpUseThrowExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\CSharpValidateFormatStringDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\EmbeddedStatementPlacement\EmbeddedStatementPlacementDiagnosticAnalyzer.cs" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>Microsoft.CodeAnalysis.CSharp.Analyzers</Import_RootNamespace> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)CSharpAnalyzersResources.resx" GenerateSource="true" Link="CSharpAnalyzersResources.resx" /> <None Include="$(MSBuildThisFileDirectory)CSharpAnalyzersResources.resx"> <SubType>Designer</SubType> </None> </ItemGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddBraces\CSharpAddBracesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddRequiredParentheses\CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertNamespaceAnalysis.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertTypeofToNameof\CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConsecutiveBracePlacement\ConsecutiveBracePlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConsecutiveStatementPlacement\CSharpConsecutiveStatementPlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\ConstructorInitializerPlacement\ConstructorInitializerPlacementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\MultipleBlankLines\CSharpMultipleBlankLinesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MatchFolderAndNamespace\CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveRedundantEquality\CSharpRemoveRedundantEqualityDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryDiscardDesignation\CSharpRemoveUnnecessaryDiscardDesignationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessarySuppressions\CSharpRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessarySuppressions\CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryParentheses\CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)AddRequiredParentheses\CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveConfusingSuppression\CSharpRemoveConfusingSuppressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionConstants.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionDiagnosticAnalyzer.Analyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FileHeaders\CSharpFileHeaderDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)FileHeaders\CSharpFileHeaderHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)InlineDeclaration\CSharpInlineDeclarationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)InvokeDelegateWithConditionalAccess\InvokeDelegateWithConditionalAccessAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeLocalFunctionStatic\MakeLocalFunctionStaticDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeLocalFunctionStatic\MakeLocalFunctionStaticHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MakeStructFieldsWritable\CSharpMakeStructFieldsWritableDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)MisplacedUsingDirectives\MisplacedUsingDirectivesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NamingStyle\CSharpNamingStyleDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)OrderModifiers\CSharpOrderModifiersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)OrderModifiers\CSharpOrderModifiersHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)PopulateSwitch\CSharpPopulateSwitchExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)PopulateSwitch\CSharpPopulateSwitchStatementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnreachableCode\CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnreachableCode\RemoveUnreachableCodeHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyBooleanExpression\CSharpSimplifyConditionalDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyInterpolation\CSharpSimplifyInterpolationHelpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyInterpolation\CSharpSimplifyInterpolationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)SimplifyLinqExpression\CSharpSimplifyLinqExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseAutoProperty\CSharpUseAutoPropertyAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCoalesceExpression\CSharpUseCoalesceExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCoalesceExpression\CSharpUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\CSharpUseCompoundAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCompoundAssignment\Utilities.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseConditionalExpression\CSharpUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseConditionalExpression\CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseDeconstruction\CSharpUseDeconstructionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseDefaultLiteral\CSharpUseDefaultLiteralDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForAccessorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForConstructorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForConversionOperatorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForIndexersHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForLocalFunctionHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForMethodsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForOperatorsHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyForPropertiesHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyHelper.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\Helpers\UseExpressionBodyHelper`1.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseExpressionBody\UseExpressionBodyDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)QualifyMemberAccess\CSharpQualifyMemberAccessDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryCast\CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryImports\CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnnecessaryParentheses\CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnusedMembers\CSharpRemoveUnusedMembersDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)RemoveUnusedParametersAndValues\CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseCollectionInitializer\CSharpUseCollectionInitializerDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitObjectCreation\CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpTypeStyleDiagnosticAnalyzerBase.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpUseExplicitTypeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseImplicitOrExplicitType\CSharpUseImplicitTypeDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseIndexOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseIndexOperatorDiagnosticAnalyzer.InfoCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.InfoCache.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\Helpers.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\MemberInfo.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseInferredMemberName\CSharpUseInferredMemberNameDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseLocalFunction\CSharpUseLocalFunctionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\CSharpUseNullPropagationDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\CSharpUseObjectInitializerDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\AnalyzedPattern.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\CSharpUsePatternCombinatorsAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpAsAndNullCheckDiagnosticAnalyzer.Analyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpAsAndNullCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpIsAndCastCheckDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpUseNotPatternDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseSimpleUsingStatement\UseSimpleUsingStatementDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\CSharpUseThrowExpressionDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\CSharpValidateFormatStringDiagnosticAnalyzer.cs" /> <Compile Include="$(MSBuildThisFileDirectory)NewLines\EmbeddedStatementPlacement\EmbeddedStatementPlacementDiagnosticAnalyzer.cs" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </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/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/StringExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions <Extension()> Friend Module StringExtensions <Extension()> Public Function TryReduceAttributeSuffix( identifierText As String, ByRef withoutSuffix As String) As Boolean ' we can't reduce _Attribute to _ because this is not a valid identifier Dim halfWidthValueText = SyntaxFacts.MakeHalfWidthIdentifier(identifierText) If halfWidthValueText.GetWithoutAttributeSuffix(isCaseSensitive:=False) <> Nothing AndAlso Not (halfWidthValueText.Length = 10 AndAlso halfWidthValueText(0) = "_") Then withoutSuffix = identifierText.Substring(0, identifierText.Length - 9) Return True End If Return False End Function <Extension()> Public Function EscapeIdentifier(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As String Dim keywordKind = SyntaxFacts.GetKeywordKind(text) Dim needsEscaping = keywordKind <> SyntaxKind.None ' REM and New must always be escaped, but there are some conditions where ' keywords are not escaped If needsEscaping AndAlso keywordKind <> SyntaxKind.REMKeyword AndAlso keywordKind <> SyntaxKind.NewKeyword Then needsEscaping = Not afterDot If needsEscaping Then Dim typeSymbol = TryCast(symbol, ITypeSymbol) needsEscaping = typeSymbol Is Nothing OrElse Not IsPredefinedType(typeSymbol) End If End If ' GetKeywordKind won't return SyntaxKind.AwaitKeyword (943836) If withinAsyncMethod AndAlso text = "Await" Then needsEscaping = True End If Return If(needsEscaping, "[" & text & "]", text) End Function <Extension()> Public Function ToIdentifierToken(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As SyntaxToken Contract.ThrowIfNull(text) Dim unescaped = text Dim wasAlreadyEscaped = False If text.Length > 2 AndAlso MakeHalfWidthIdentifier(text.First()) = "[" AndAlso MakeHalfWidthIdentifier(text.Last()) = "]" Then unescaped = text.Substring(1, text.Length() - 2) wasAlreadyEscaped = True End If Dim escaped = EscapeIdentifier(text, afterDot, symbol, withinAsyncMethod) Dim token = If(escaped.Length > 0 AndAlso escaped(0) = "["c, SyntaxFactory.Identifier(escaped, isBracketed:=True, identifierText:=unescaped, typeCharacter:=TypeCharacter.None), SyntaxFactory.Identifier(text)) If Not wasAlreadyEscaped Then token = token.WithAdditionalAnnotations(Simplifier.Annotation) End If Return token End Function <Extension()> Public Function ToModifiedIdentifier(text As String) As ModifiedIdentifierSyntax Return SyntaxFactory.ModifiedIdentifier(text.ToIdentifierToken) End Function <Extension()> Public Function ToIdentifierName(text As String) As IdentifierNameSyntax Contract.ThrowIfNull(text) Return SyntaxFactory.IdentifierName(text.ToIdentifierToken()).WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function IsPredefinedType(type As ITypeSymbol) As Boolean Select Case type.SpecialType Case SpecialType.System_Boolean, SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32, SpecialType.System_UInt32, SpecialType.System_Int64, SpecialType.System_UInt64, SpecialType.System_Single, SpecialType.System_Double, SpecialType.System_Decimal, SpecialType.System_DateTime, SpecialType.System_Char, SpecialType.System_String, SpecialType.System_Object Return True Case Else Return False End Select End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions <Extension()> Friend Module StringExtensions <Extension()> Public Function TryReduceAttributeSuffix( identifierText As String, ByRef withoutSuffix As String) As Boolean ' we can't reduce _Attribute to _ because this is not a valid identifier Dim halfWidthValueText = SyntaxFacts.MakeHalfWidthIdentifier(identifierText) If halfWidthValueText.GetWithoutAttributeSuffix(isCaseSensitive:=False) <> Nothing AndAlso Not (halfWidthValueText.Length = 10 AndAlso halfWidthValueText(0) = "_") Then withoutSuffix = identifierText.Substring(0, identifierText.Length - 9) Return True End If Return False End Function <Extension()> Public Function EscapeIdentifier(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As String Dim keywordKind = SyntaxFacts.GetKeywordKind(text) Dim needsEscaping = keywordKind <> SyntaxKind.None ' REM and New must always be escaped, but there are some conditions where ' keywords are not escaped If needsEscaping AndAlso keywordKind <> SyntaxKind.REMKeyword AndAlso keywordKind <> SyntaxKind.NewKeyword Then needsEscaping = Not afterDot If needsEscaping Then Dim typeSymbol = TryCast(symbol, ITypeSymbol) needsEscaping = typeSymbol Is Nothing OrElse Not IsPredefinedType(typeSymbol) End If End If ' GetKeywordKind won't return SyntaxKind.AwaitKeyword (943836) If withinAsyncMethod AndAlso text = "Await" Then needsEscaping = True End If Return If(needsEscaping, "[" & text & "]", text) End Function <Extension()> Public Function ToIdentifierToken(text As String, Optional afterDot As Boolean = False, Optional symbol As ISymbol = Nothing, Optional withinAsyncMethod As Boolean = False) As SyntaxToken Contract.ThrowIfNull(text) Dim unescaped = text Dim wasAlreadyEscaped = False If text.Length > 2 AndAlso MakeHalfWidthIdentifier(text.First()) = "[" AndAlso MakeHalfWidthIdentifier(text.Last()) = "]" Then unescaped = text.Substring(1, text.Length() - 2) wasAlreadyEscaped = True End If Dim escaped = EscapeIdentifier(text, afterDot, symbol, withinAsyncMethod) Dim token = If(escaped.Length > 0 AndAlso escaped(0) = "["c, SyntaxFactory.Identifier(escaped, isBracketed:=True, identifierText:=unescaped, typeCharacter:=TypeCharacter.None), SyntaxFactory.Identifier(text)) If Not wasAlreadyEscaped Then token = token.WithAdditionalAnnotations(Simplifier.Annotation) End If Return token End Function <Extension()> Public Function ToModifiedIdentifier(text As String) As ModifiedIdentifierSyntax Return SyntaxFactory.ModifiedIdentifier(text.ToIdentifierToken) End Function <Extension()> Public Function ToIdentifierName(text As String) As IdentifierNameSyntax Contract.ThrowIfNull(text) Return SyntaxFactory.IdentifierName(text.ToIdentifierToken()).WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function IsPredefinedType(type As ITypeSymbol) As Boolean Select Case type.SpecialType Case SpecialType.System_Boolean, SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32, SpecialType.System_UInt32, SpecialType.System_Int64, SpecialType.System_UInt64, SpecialType.System_Single, SpecialType.System_Double, SpecialType.System_Decimal, SpecialType.System_DateTime, SpecialType.System_Char, SpecialType.System_String, SpecialType.System_Object Return True Case Else Return False End Select End Function End Module 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/CSharp/Portable/Completion/KeywordRecommenders/YieldKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 YieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public YieldKeywordRecommender() : base(SyntaxKind.YieldKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsStatementContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 YieldKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public YieldKeywordRecommender() : base(SyntaxKind.YieldKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsStatementContext; } }
-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/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement { internal abstract class AbstractConsecutiveStatementPlacementDiagnosticAnalyzer<TExecutableStatementSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TExecutableStatementSyntax : SyntaxNode { private readonly ISyntaxFacts _syntaxFacts; protected AbstractConsecutiveStatementPlacementDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveStatementPlacement, CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, LanguageNames.CSharp, new LocalizableResourceString( nameof(AnalyzersResources.Blank_line_required_between_block_and_subsequent_statement), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } protected abstract bool IsBlockLikeStatement(SyntaxNode node); protected abstract Location GetDiagnosticLocation(SyntaxNode block); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var cancellationToken = context.CancellationToken; var tree = context.Tree; var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language); if (option.Value) return; Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken) { if (node.ContainsDiagnostics && node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (IsBlockLikeStatement(node)) ProcessBlockLikeStatement(context, severity, node); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!, cancellationToken); } } private void ProcessBlockLikeStatement(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode block) { // Don't examine broken blocks. var endToken = block.GetLastToken(); if (endToken.IsMissing) return; // If the close brace itself doesn't have a newline, then ignore this. This is a case of series of // statements on the same line. if (!endToken.TrailingTrivia.Any()) return; if (!_syntaxFacts.IsEndOfLineTrivia(endToken.TrailingTrivia.Last())) return; // Grab whatever comes after the close brace. If it's not the start of a statement, ignore it. var nextToken = endToken.GetNextToken(); var nextTokenContainingStatement = nextToken.Parent?.FirstAncestorOrSelf<TExecutableStatementSyntax>(); if (nextTokenContainingStatement == null) return; if (nextToken != nextTokenContainingStatement.GetFirstToken()) return; // There has to be at least a blank line between the end of the block and the start of the next statement. foreach (var trivia in nextToken.LeadingTrivia) { // If there's a blank line between the brace and the next token, we're all set. if (_syntaxFacts.IsEndOfLineTrivia(trivia)) return; if (_syntaxFacts.IsWhitespaceTrivia(trivia)) continue; // got something that wasn't whitespace. Bail out as we don't want to place any restrictions on this code. return; } context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, GetDiagnosticLocation(block), severity, additionalLocations: ImmutableArray.Create(nextToken.GetLocation()), properties: null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement { internal abstract class AbstractConsecutiveStatementPlacementDiagnosticAnalyzer<TExecutableStatementSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TExecutableStatementSyntax : SyntaxNode { private readonly ISyntaxFacts _syntaxFacts; protected AbstractConsecutiveStatementPlacementDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveStatementPlacement, CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, LanguageNames.CSharp, new LocalizableResourceString( nameof(AnalyzersResources.Blank_line_required_between_block_and_subsequent_statement), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } protected abstract bool IsBlockLikeStatement(SyntaxNode node); protected abstract Location GetDiagnosticLocation(SyntaxNode block); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var cancellationToken = context.CancellationToken; var tree = context.Tree; var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language); if (option.Value) return; Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken) { if (node.ContainsDiagnostics && node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (IsBlockLikeStatement(node)) ProcessBlockLikeStatement(context, severity, node); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!, cancellationToken); } } private void ProcessBlockLikeStatement(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode block) { // Don't examine broken blocks. var endToken = block.GetLastToken(); if (endToken.IsMissing) return; // If the close brace itself doesn't have a newline, then ignore this. This is a case of series of // statements on the same line. if (!endToken.TrailingTrivia.Any()) return; if (!_syntaxFacts.IsEndOfLineTrivia(endToken.TrailingTrivia.Last())) return; // Grab whatever comes after the close brace. If it's not the start of a statement, ignore it. var nextToken = endToken.GetNextToken(); var nextTokenContainingStatement = nextToken.Parent?.FirstAncestorOrSelf<TExecutableStatementSyntax>(); if (nextTokenContainingStatement == null) return; if (nextToken != nextTokenContainingStatement.GetFirstToken()) return; // There has to be at least a blank line between the end of the block and the start of the next statement. foreach (var trivia in nextToken.LeadingTrivia) { // If there's a blank line between the brace and the next token, we're all set. if (_syntaxFacts.IsEndOfLineTrivia(trivia)) return; if (_syntaxFacts.IsWhitespaceTrivia(trivia)) continue; // got something that wasn't whitespace. Bail out as we don't want to place any restrictions on this code. return; } context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, GetDiagnosticLocation(block), severity, additionalLocations: ImmutableArray.Create(nextToken.GetLocation()), properties: 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.
./docs/compilers/Deterministic Inputs.md
Deterministic Inputs ==================== The C# and VB compilers are fully deterministic when the `/deterministic` option is specified (this is the default in the .NET SDK). This means that the "same inputs" will cause the compilers to produce the "same outputs" byte for byte. The following are considered inputs to the compiler for the purpose of determinism: - The sequence of command-line parameters (order is important) - The precise version of the compiler used and the files included in its deployment: reference assemblies, rsp, etc ... - Current full directory path (you can reduce this to a relative path; see https://github.com/dotnet/roslyn/issues/949) - (Binary) contents of all files explicitly passed to the compiler, directly or indirectly, including - source files - referenced assemblies - referenced modules - resources - the strong name key file - `@` response files - Analyzers - Generators - Rulesets - "additional files" that may be used by analyzers and generators - The current culture if `/preferreduilang` is not specified (for the language in which diagnostics and exception messages are produced). - The current OS code page if `/codepage` is not specified and any of the input source files do not have BOM and are not UTF-8 encoded. - The existence, non-existence, and contents of files on the compiler's search paths (specified, e.g. by `/lib` or `/recurse`) - The CLR platform on which the compiler is run: - The result of `double` arithmetic performed for constant-folding may use excess precision on some platforms. - The compiler uses Unicode tables provided by the platform. - The version of the zlib library that the CLR uses to implement compression (when `/embed` or `/debug:embedded` is used). - The value of `%LIBPATH%`, as it can affect reference discovery if not fully qualified and how the runtime handles analyzer / generator dependency loading. - The full path of source files although `/pathmap` can be used to normalize this between compiles of the same code in different root directories. At the moment the compiler also depends on the time of day and random numbers for GUIDs, so it is not deterministic unless you specify `/deterministic`.
Deterministic Inputs ==================== The C# and VB compilers are fully deterministic when the `/deterministic` option is specified (this is the default in the .NET SDK). This means that the "same inputs" will cause the compilers to produce the "same outputs" byte for byte. The following are considered inputs to the compiler for the purpose of determinism: - The sequence of command-line parameters (order is important) - The precise version of the compiler used and the files included in its deployment: reference assemblies, rsp, etc ... - Current full directory path (you can reduce this to a relative path; see https://github.com/dotnet/roslyn/issues/949) - (Binary) contents of all files explicitly passed to the compiler, directly or indirectly, including - source files - referenced assemblies - referenced modules - resources - the strong name key file - `@` response files - Analyzers - Generators - Rulesets - "additional files" that may be used by analyzers and generators - The current culture if `/preferreduilang` is not specified (for the language in which diagnostics and exception messages are produced). - The current OS code page if `/codepage` is not specified and any of the input source files do not have BOM and are not UTF-8 encoded. - The existence, non-existence, and contents of files on the compiler's search paths (specified, e.g. by `/lib` or `/recurse`) - The CLR platform on which the compiler is run: - The result of `double` arithmetic performed for constant-folding may use excess precision on some platforms. - The compiler uses Unicode tables provided by the platform. - The version of the zlib library that the CLR uses to implement compression (when `/embed` or `/debug:embedded` is used). - The value of `%LIBPATH%`, as it can affect reference discovery if not fully qualified and how the runtime handles analyzer / generator dependency loading. - The full path of source files although `/pathmap` can be used to normalize this between compiles of the same code in different root directories. At the moment the compiler also depends on the time of day and random numbers for GUIDs, so it is not deterministic unless you specify `/deterministic`.
-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/PreprocessingSymbol.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> ''' Represents a preprocessing conditional compilation symbol. ''' </summary> Friend NotInheritable Class PreprocessingSymbol Inherits Symbol Implements IPreprocessingSymbol Private ReadOnly _name As String Friend Sub New(name As String) MyBase.New() _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of VisualBasicSyntaxNode)(Locations) End Get End Property Public Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Preprocessing End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True ElseIf obj Is Nothing Then Return False End If Dim other As PreprocessingSymbol = TryCast(obj, PreprocessingSymbol) Return other IsNot Nothing AndAlso IdentifierComparison.Equals(Me.Name, other.Name) End Function Public Overrides Function GetHashCode() As Integer Return Me.Name.GetHashCode() End Function Public Overloads Overrides Sub Accept(visitor As SymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Public Overloads Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Throw New NotSupportedException() 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> ''' Represents a preprocessing conditional compilation symbol. ''' </summary> Friend NotInheritable Class PreprocessingSymbol Inherits Symbol Implements IPreprocessingSymbol Private ReadOnly _name As String Friend Sub New(name As String) MyBase.New() _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of VisualBasicSyntaxNode)(Locations) End Get End Property Public Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Preprocessing End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True ElseIf obj Is Nothing Then Return False End If Dim other As PreprocessingSymbol = TryCast(obj, PreprocessingSymbol) Return other IsNot Nothing AndAlso IdentifierComparison.Equals(Me.Name, other.Name) End Function Public Overrides Function GetHashCode() As Integer Return Me.Name.GetHashCode() End Function Public Overloads Overrides Sub Accept(visitor As SymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Public Overloads Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Throw New NotSupportedException() 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/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithPrevious.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements <Trait(Traits.Feature, Traits.Features.CodeActionsMergeConsecutiveIfStatements)> Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicMergeConsecutiveIfStatementsCodeRefactoringProvider() End Function <Theory> <InlineData("[||]elseif b then")> <InlineData("el[||]seif b then")> <InlineData("elseif[||] b then")> <InlineData("elseif b [||]then")> <InlineData("elseif b th[||]en")> <InlineData("elseif b then[||]")> <InlineData("[|elseif|] b then")> <InlineData("[|elseif b then|]")> Public Async Function MergedOnElseIfSpans(elseIfLine As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if a then {elseIfLine} end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfExtendedStatementSelection() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [| elseif b then |] end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfFullSelectionWithoutElseClause() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [|elseif b then System.Console.WriteLine()|] else end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfExtendedFullSelectionWithoutElseClause() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [| elseif b then System.Console.WriteLine() |] else end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfFullSelectionWithElseClause() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [|elseif b then System.Console.WriteLine() else end if|] end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfExtendedFullSelectionWithElseClause() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [| elseif b then System.Console.WriteLine() else end if |] end sub end class") End Function <Theory> <InlineData("elseif [||]b then")> <InlineData("[|else|]if b then")> <InlineData("[|elseif b|] then")> <InlineData("elseif [|b|] then")> <InlineData("elseif b [|then|]")> Public Async Function NotMergedOnElseIfSpans(elseIfLine As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if a then {elseIfLine} end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfOverreachingSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [|elseif b then |]end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfBodyStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then return elseif b then [|return|] end if end sub end class") End Function <Fact> Public Async Function NotMergedOnEndIfStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then elseif b then [|end if|] end sub end class") End Function <Fact> Public Async Function NotMergedOnEndIfStatementCaret() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then elseif b then [||]end if end sub end class") End Function <Fact> Public Async Function NotMergedOnSingleIf() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [||]if b then end if end sub end class") End Function <Fact> Public Async Function MergedWithOrElseExpressions() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b then [||]elseif c orelse d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b OrElse c orelse d then end if end sub end class") End Function <Fact> Public Async Function MergedWithAndAlsoExpressionNotParenthesized1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b then [||]elseif c orelse d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b OrElse c orelse d then end if end sub end class") End Function <Fact> Public Async Function MergedWithAndAlsoExpressionNotParenthesized2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b then [||]elseif c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b OrElse c andalso d then end if end sub end class") End Function <Fact> Public Async Function MergedWithExclusiveOrExpressionParenthesized1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a xor b then [||]elseif c = d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a xor b) OrElse c = d then end if end sub end class") End Function <Fact> Public Async Function MergedWithExclusiveOrExpressionParenthesized2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a = b then [||]elseif c xor d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a = b OrElse (c xor d) then end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(a) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements3() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements4() As Task ' Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) [||]elseif b then using nothing System.Console.WriteLine(a) end using end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() else System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseNestedIfStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentPartOfElseIf() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() elseif b then System.Console.WriteLine(a) [||]elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() elseif b OrElse a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements <Trait(Traits.Feature, Traits.Features.CodeActionsMergeConsecutiveIfStatements)> Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicMergeConsecutiveIfStatementsCodeRefactoringProvider() End Function <Theory> <InlineData("[||]elseif b then")> <InlineData("el[||]seif b then")> <InlineData("elseif[||] b then")> <InlineData("elseif b [||]then")> <InlineData("elseif b th[||]en")> <InlineData("elseif b then[||]")> <InlineData("[|elseif|] b then")> <InlineData("[|elseif b then|]")> Public Async Function MergedOnElseIfSpans(elseIfLine As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if a then {elseIfLine} end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfExtendedStatementSelection() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [| elseif b then |] end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfFullSelectionWithoutElseClause() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [|elseif b then System.Console.WriteLine()|] else end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else end if end sub end class") End Function <Fact> Public Async Function MergedOnElseIfExtendedFullSelectionWithoutElseClause() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [| elseif b then System.Console.WriteLine() |] else end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfFullSelectionWithElseClause() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [|elseif b then System.Console.WriteLine() else end if|] end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfExtendedFullSelectionWithElseClause() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [| elseif b then System.Console.WriteLine() else end if |] end sub end class") End Function <Theory> <InlineData("elseif [||]b then")> <InlineData("[|else|]if b then")> <InlineData("[|elseif b|] then")> <InlineData("elseif [|b|] then")> <InlineData("elseif b [|then|]")> Public Async Function NotMergedOnElseIfSpans(elseIfLine As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if a then {elseIfLine} end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfOverreachingSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [|elseif b then |]end if end sub end class") End Function <Fact> Public Async Function NotMergedOnElseIfBodyStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then return elseif b then [|return|] end if end sub end class") End Function <Fact> Public Async Function NotMergedOnEndIfStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then elseif b then [|end if|] end sub end class") End Function <Fact> Public Async Function NotMergedOnEndIfStatementCaret() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then elseif b then [||]end if end sub end class") End Function <Fact> Public Async Function NotMergedOnSingleIf() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [||]if b then end if end sub end class") End Function <Fact> Public Async Function MergedWithOrElseExpressions() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b then [||]elseif c orelse d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b OrElse c orelse d then end if end sub end class") End Function <Fact> Public Async Function MergedWithAndAlsoExpressionNotParenthesized1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b then [||]elseif c orelse d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b OrElse c orelse d then end if end sub end class") End Function <Fact> Public Async Function MergedWithAndAlsoExpressionNotParenthesized2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b then [||]elseif c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a orelse b OrElse c andalso d then end if end sub end class") End Function <Fact> Public Async Function MergedWithExclusiveOrExpressionParenthesized1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a xor b then [||]elseif c = d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a xor b) OrElse c = d then end if end sub end class") End Function <Fact> Public Async Function MergedWithExclusiveOrExpressionParenthesized2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a = b then [||]elseif c xor d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a = b OrElse (c xor d) then end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(a) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) System.Console.WriteLine(b) [||]elseif b then System.Console.WriteLine(a) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements3() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) [||]elseif b then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoParentWithUnmatchingStatements4() As Task ' Do not consider the using statement to be a simple block (as might be suggested by some language-agnostic helpers). Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine(a) [||]elseif b then using nothing System.Console.WriteLine(a) end using end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() else System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() else System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseNestedIfStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentWithElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() [||]elseif b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function MergedIntoParentPartOfElseIf() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() elseif b then System.Console.WriteLine(a) [||]elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then System.Console.WriteLine() elseif b OrElse a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") 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/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class StateMachineRewriter { protected readonly BoundStatement body; protected readonly MethodSymbol method; protected readonly BindingDiagnosticBag diagnostics; protected readonly SyntheticBoundNodeFactory F; protected readonly SynthesizedContainer stateMachineType; protected readonly VariableSlotAllocator slotAllocatorOpt; protected readonly SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals; protected FieldSymbol stateField; protected IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies; protected int nextFreeHoistedLocalSlot; protected IOrderedReadOnlySet<Symbol> hoistedVariables; protected Dictionary<Symbol, CapturedSymbolReplacement> initialParameters; protected FieldSymbol initialThreadIdField; protected StateMachineRewriter( BoundStatement body, MethodSymbol method, SynthesizedContainer stateMachineType, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(body != null); Debug.Assert(method != null); Debug.Assert((object)stateMachineType != null); Debug.Assert(compilationState != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); this.body = body; this.method = method; this.stateMachineType = stateMachineType; this.slotAllocatorOpt = slotAllocatorOpt; this.synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser(); this.diagnostics = diagnostics; this.F = new SyntheticBoundNodeFactory(method, body.Syntax, compilationState, diagnostics); Debug.Assert(TypeSymbol.Equals(F.CurrentType, method.ContainingType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(F.Syntax == body.Syntax); } /// <summary> /// True if the initial values of locals in the rewritten method and the initial thread ID need to be preserved. (e.g. enumerable iterator methods and async-enumerable iterator methods) /// </summary> protected abstract bool PreserveInitialParameterValuesAndThreadId { get; } /// <summary> /// Add fields to the state machine class that control the state machine. /// </summary> protected abstract void GenerateControlFields(); /// <summary> /// Initialize the state machine class. /// </summary> protected abstract void InitializeStateMachine(ArrayBuilder<BoundStatement> bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal); /// <summary> /// Generate implementation-specific state machine initialization for the kickoff method body. /// </summary> protected abstract BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies); /// <summary> /// Generate implementation-specific state machine member method implementations. /// </summary> protected abstract void GenerateMethodImplementations(); protected BoundStatement Rewrite() { if (this.body.HasErrors) { return this.body; } F.OpenNestedType(stateMachineType); GenerateControlFields(); if (PreserveInitialParameterValuesAndThreadId && CanGetThreadId()) { // if it is an enumerable or async-enumerable, and either Environment.CurrentManagedThreadId or Thread.ManagedThreadId are available // add a field: int initialThreadId initialThreadIdField = F.StateMachineField(F.SpecialType(SpecialType.System_Int32), GeneratedNames.MakeIteratorCurrentThreadIdFieldName()); } // fields for the initial values of all the parameters of the method if (PreserveInitialParameterValuesAndThreadId) { initialParameters = new Dictionary<Symbol, CapturedSymbolReplacement>(); } // fields for the captured variables of the method var variablesToHoist = IteratorAndAsyncCaptureWalker.Analyze(F.Compilation, method, body, diagnostics.DiagnosticBag); if (diagnostics.HasAnyErrors()) { // Avoid triggering assertions in further lowering. return new BoundBadStatement(F.Syntax, ImmutableArray<BoundNode>.Empty, hasErrors: true); } CreateNonReusableLocalProxies(variablesToHoist, out this.nonReusableLocalProxies, out this.nextFreeHoistedLocalSlot); this.hoistedVariables = variablesToHoist; GenerateMethodImplementations(); // Return a replacement body for the kickoff method return GenerateKickoffMethodBody(); } private void CreateNonReusableLocalProxies( IEnumerable<Symbol> variablesToHoist, out IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies, out int nextFreeHoistedLocalSlot) { var proxiesBuilder = new Dictionary<Symbol, CapturedSymbolReplacement>(); var typeMap = stateMachineType.TypeMap; bool isDebugBuild = F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug; bool mapToPreviousFields = isDebugBuild && slotAllocatorOpt != null; nextFreeHoistedLocalSlot = mapToPreviousFields ? slotAllocatorOpt.PreviousHoistedLocalSlotCount : 0; foreach (var variable in variablesToHoist) { Debug.Assert(variable.Kind == SymbolKind.Local || variable.Kind == SymbolKind.Parameter); if (variable.Kind == SymbolKind.Local) { var local = (LocalSymbol)variable; var synthesizedKind = local.SynthesizedKind; if (!synthesizedKind.MustSurviveStateMachineSuspension()) { continue; } // no need to hoist constants if (local.IsConst) { continue; } if (local.RefKind != RefKind.None) { // we'll create proxies for these variables later: Debug.Assert(synthesizedKind == SynthesizedLocalKind.Spill); continue; } Debug.Assert(local.RefKind == RefKind.None); StateMachineFieldSymbol field = null; if (ShouldPreallocateNonReusableProxy(local)) { // variable needs to be hoisted var fieldType = typeMap.SubstituteType(local.Type).Type; LocalDebugId id; int slotIndex = -1; if (isDebugBuild) { // Calculate local debug id. // // EnC: When emitting the baseline (gen 0) the id is stored in a custom debug information attached to the kickoff method. // When emitting a delta the id is only used to map to the existing field in the previous generation. SyntaxNode declaratorSyntax = local.GetDeclaratorSyntax(); int syntaxOffset = method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(declaratorSyntax), declaratorSyntax.SyntaxTree); int ordinal = synthesizedLocalOrdinals.AssignLocalOrdinal(synthesizedKind, syntaxOffset); id = new LocalDebugId(syntaxOffset, ordinal); // map local id to the previous id, if available: int previousSlotIndex; if (mapToPreviousFields && slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex( declaratorSyntax, F.ModuleBuilderOpt.Translate(fieldType, declaratorSyntax, diagnostics.DiagnosticBag), synthesizedKind, id, diagnostics.DiagnosticBag, out previousSlotIndex)) { slotIndex = previousSlotIndex; } } else { id = LocalDebugId.None; } if (slotIndex == -1) { slotIndex = nextFreeHoistedLocalSlot++; } string fieldName = GeneratedNames.MakeHoistedLocalFieldName(synthesizedKind, slotIndex, local.Name); field = F.StateMachineField(fieldType, fieldName, new LocalSlotDebugInfo(synthesizedKind, id), slotIndex); } if (field != null) { proxiesBuilder.Add(local, new CapturedToStateMachineFieldReplacement(field, isReusable: false)); } } else { var parameter = (ParameterSymbol)variable; if (parameter.IsThis) { var containingType = method.ContainingType; var proxyField = F.StateMachineField(containingType, GeneratedNames.ThisProxyFieldName(), isPublic: true, isThis: true); proxiesBuilder.Add(parameter, new CapturedToStateMachineFieldReplacement(proxyField, isReusable: false)); if (PreserveInitialParameterValuesAndThreadId) { var initialThis = containingType.IsStructType() ? F.StateMachineField(containingType, GeneratedNames.StateMachineThisParameterProxyName(), isPublic: true, isThis: true) : proxyField; initialParameters.Add(parameter, new CapturedToStateMachineFieldReplacement(initialThis, isReusable: false)); } } else { // The field needs to be public iff it is initialized directly from the kickoff method // (i.e. not for IEnumerable which loads the values from parameter proxies). var proxyField = F.StateMachineField(typeMap.SubstituteType(parameter.Type).Type, parameter.Name, isPublic: !PreserveInitialParameterValuesAndThreadId); proxiesBuilder.Add(parameter, new CapturedToStateMachineFieldReplacement(proxyField, isReusable: false)); if (PreserveInitialParameterValuesAndThreadId) { var field = F.StateMachineField(typeMap.SubstituteType(parameter.Type).Type, GeneratedNames.StateMachineParameterProxyFieldName(parameter.Name), isPublic: true); initialParameters.Add(parameter, new CapturedToStateMachineFieldReplacement(field, isReusable: false)); } } } } proxies = proxiesBuilder; } private bool ShouldPreallocateNonReusableProxy(LocalSymbol local) { var synthesizedKind = local.SynthesizedKind; var optimizationLevel = F.Compilation.Options.OptimizationLevel; // do not preallocate proxy fields for user defined locals in release // otherwise we will be allocating fields for all locals even when fields can be reused // see https://github.com/dotnet/roslyn/issues/15290 if (optimizationLevel == OptimizationLevel.Release && synthesizedKind == SynthesizedLocalKind.UserDefined) { return false; } return !synthesizedKind.IsSlotReusable(optimizationLevel); } private BoundStatement GenerateKickoffMethodBody() { F.CurrentFunction = method; var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var frameType = method.IsGenericMethod ? stateMachineType.Construct(method.TypeArgumentsWithAnnotations, unbound: false) : stateMachineType; LocalSymbol stateMachineVariable = F.SynthesizedLocal(frameType, null); InitializeStateMachine(bodyBuilder, frameType, stateMachineVariable); // plus code to initialize all of the parameter proxies result.proxy var proxies = PreserveInitialParameterValuesAndThreadId ? initialParameters : nonReusableLocalProxies; bodyBuilder.Add(GenerateStateMachineCreation(stateMachineVariable, frameType, proxies)); return F.Block( ImmutableArray.Create(stateMachineVariable), bodyBuilder.ToImmutableAndFree()); } protected BoundStatement GenerateParameterStorage(LocalSymbol stateMachineVariable, IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies) { var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // starting with the "this" proxy if (!method.IsStatic) { Debug.Assert((object)method.ThisParameter != null); CapturedSymbolReplacement proxy; if (proxies.TryGetValue(method.ThisParameter, out proxy)) { bodyBuilder.Add(F.Assignment(proxy.Replacement(F.Syntax, frameType1 => F.Local(stateMachineVariable)), F.This())); } } foreach (var parameter in method.Parameters) { CapturedSymbolReplacement proxy; if (proxies.TryGetValue(parameter, out proxy)) { bodyBuilder.Add(F.Assignment(proxy.Replacement(F.Syntax, frameType1 => F.Local(stateMachineVariable)), F.Parameter(parameter))); } } return F.Block(bodyBuilder.ToImmutableAndFree()); } protected SynthesizedImplementationMethod OpenMethodImplementation( MethodSymbol methodToImplement, string methodName = null, bool hasMethodBodyDependency = false) { var result = new SynthesizedStateMachineDebuggerHiddenMethod(methodName, methodToImplement, (StateMachineTypeSymbol)F.CurrentType, null, hasMethodBodyDependency); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, result.GetCciAdapter()); F.CurrentFunction = result; return result; } protected MethodSymbol OpenPropertyImplementation(MethodSymbol getterToImplement) { var prop = new SynthesizedStateMachineProperty(getterToImplement, (StateMachineTypeSymbol)F.CurrentType); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, prop.GetCciAdapter()); var getter = prop.GetMethod; F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, getter.GetCciAdapter()); F.CurrentFunction = getter; return getter; } protected SynthesizedImplementationMethod OpenMoveNextMethodImplementation(MethodSymbol methodToImplement) { var result = new SynthesizedStateMachineMoveNextMethod(methodToImplement, (StateMachineTypeSymbol)F.CurrentType); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, result.GetCciAdapter()); F.CurrentFunction = result; return result; } /// <summary> /// Produce Environment.CurrentManagedThreadId if available, otherwise CurrentThread.ManagedThreadId /// </summary> protected BoundExpression MakeCurrentThreadId() { Debug.Assert(CanGetThreadId()); // .NET Core has removed the Thread class. We can get the managed thread id by making a call to // Environment.CurrentManagedThreadId. If that method is not present (pre 4.5) fall back to the old behavior. var currentManagedThreadIdProperty = (PropertySymbol)F.WellKnownMember(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional: true); if ((object)currentManagedThreadIdProperty != null) { MethodSymbol currentManagedThreadIdMethod = currentManagedThreadIdProperty.GetMethod; if ((object)currentManagedThreadIdMethod != null) { return F.Call(null, currentManagedThreadIdMethod); } } return F.Property(F.Property(WellKnownMember.System_Threading_Thread__CurrentThread), WellKnownMember.System_Threading_Thread__ManagedThreadId); } /// <summary> /// Generate the GetEnumerator() method for iterators and GetAsyncEnumerator() for async-iterators. /// </summary> protected SynthesizedImplementationMethod GenerateIteratorGetEnumerator(MethodSymbol getEnumeratorMethod, ref BoundExpression managedThreadId, int initialState) { // Produces: // {StateMachineType} result; // if (this.initialThreadId == {managedThreadId} && this.state == -2) // { // this.state = {initialState}; // extraReset // result = this; // } // else // { // result = new {StateMachineType}({initialState}); // } // // result.parameter = this.parameterProxy; // OR more complex initialization for async-iterator parameter marked with [EnumeratorCancellation] // The implementation doesn't depend on the method body of the iterator method. // Only on its parameters and staticness. var getEnumerator = OpenMethodImplementation( getEnumeratorMethod, hasMethodBodyDependency: false); var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // {StateMachineType} result; var resultVariable = F.SynthesizedLocal(stateMachineType, null); // result = new {StateMachineType}({initialState}) BoundStatement makeIterator = F.Assignment(F.Local(resultVariable), F.New(stateMachineType.Constructor, F.Literal(initialState))); var thisInitialized = F.GenerateLabel("thisInitialized"); if ((object)initialThreadIdField != null) { managedThreadId = MakeCurrentThreadId(); var thenBuilder = ArrayBuilder<BoundStatement>.GetInstance(4); GenerateResetInstance(thenBuilder, initialState); thenBuilder.Add( // result = this; F.Assignment(F.Local(resultVariable), F.This())); if (method.IsStatic || method.ThisParameter.Type.IsReferenceType) { // if this is a reference type, no need to copy it since it is not assignable thenBuilder.Add( // goto thisInitialized; F.Goto(thisInitialized)); } makeIterator = F.If( // if (this.state == -2 && this.initialThreadId == Thread.CurrentThread.ManagedThreadId) condition: F.LogicalAnd( F.IntEqual(F.Field(F.This(), stateField), F.Literal(StateMachineStates.FinishedStateMachine)), F.IntEqual(F.Field(F.This(), initialThreadIdField), managedThreadId)), thenClause: F.Block(thenBuilder.ToImmutableAndFree()), elseClauseOpt: makeIterator); } bodyBuilder.Add(makeIterator); // Initialize all the parameter copies var copySrc = initialParameters; var copyDest = nonReusableLocalProxies; if (!method.IsStatic) { // starting with "this" CapturedSymbolReplacement proxy; if (copyDest.TryGetValue(method.ThisParameter, out proxy)) { bodyBuilder.Add( F.Assignment( proxy.Replacement(F.Syntax, stateMachineType => F.Local(resultVariable)), copySrc[method.ThisParameter].Replacement(F.Syntax, stateMachineType => F.This()))); } } bodyBuilder.Add(F.Label(thisInitialized)); foreach (var parameter in method.Parameters) { CapturedSymbolReplacement proxy; if (copyDest.TryGetValue(parameter, out proxy)) { // result.parameter BoundExpression resultParameter = proxy.Replacement(F.Syntax, stateMachineType => F.Local(resultVariable)); // this.parameterProxy BoundExpression parameterProxy = copySrc[parameter].Replacement(F.Syntax, stateMachineType => F.This()); BoundStatement copy = InitializeParameterField(getEnumeratorMethod, parameter, resultParameter, parameterProxy); bodyBuilder.Add(copy); } } bodyBuilder.Add(F.Return(F.Local(resultVariable))); F.CloseMethod(F.Block(ImmutableArray.Create(resultVariable), bodyBuilder.ToImmutableAndFree())); return getEnumerator; } /// <summary> /// Generate logic to reset the current instance (rather than creating a new instance) /// </summary> protected virtual void GenerateResetInstance(ArrayBuilder<BoundStatement> builder, int initialState) { builder.Add( // this.state = {initialState}; F.Assignment(F.Field(F.This(), stateField), F.Literal(initialState))); } protected virtual BoundStatement InitializeParameterField(MethodSymbol getEnumeratorMethod, ParameterSymbol parameter, BoundExpression resultParameter, BoundExpression parameterProxy) { Debug.Assert(!method.IsIterator || !method.IsAsync); // an override handles async-iterators // result.parameter = this.parameterProxy; return F.Assignment(resultParameter, parameterProxy); } /// <summary> /// Returns true if either Thread.ManagedThreadId or Environment.CurrentManagedThreadId are available /// </summary> protected bool CanGetThreadId() { return (object)F.WellKnownMember(WellKnownMember.System_Threading_Thread__ManagedThreadId, isOptional: true) != null || (object)F.WellKnownMember(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional: true) != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class StateMachineRewriter { protected readonly BoundStatement body; protected readonly MethodSymbol method; protected readonly BindingDiagnosticBag diagnostics; protected readonly SyntheticBoundNodeFactory F; protected readonly SynthesizedContainer stateMachineType; protected readonly VariableSlotAllocator slotAllocatorOpt; protected readonly SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals; protected FieldSymbol stateField; protected IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies; protected int nextFreeHoistedLocalSlot; protected IOrderedReadOnlySet<Symbol> hoistedVariables; protected Dictionary<Symbol, CapturedSymbolReplacement> initialParameters; protected FieldSymbol initialThreadIdField; protected StateMachineRewriter( BoundStatement body, MethodSymbol method, SynthesizedContainer stateMachineType, VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(body != null); Debug.Assert(method != null); Debug.Assert((object)stateMachineType != null); Debug.Assert(compilationState != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); this.body = body; this.method = method; this.stateMachineType = stateMachineType; this.slotAllocatorOpt = slotAllocatorOpt; this.synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser(); this.diagnostics = diagnostics; this.F = new SyntheticBoundNodeFactory(method, body.Syntax, compilationState, diagnostics); Debug.Assert(TypeSymbol.Equals(F.CurrentType, method.ContainingType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(F.Syntax == body.Syntax); } /// <summary> /// True if the initial values of locals in the rewritten method and the initial thread ID need to be preserved. (e.g. enumerable iterator methods and async-enumerable iterator methods) /// </summary> protected abstract bool PreserveInitialParameterValuesAndThreadId { get; } /// <summary> /// Add fields to the state machine class that control the state machine. /// </summary> protected abstract void GenerateControlFields(); /// <summary> /// Initialize the state machine class. /// </summary> protected abstract void InitializeStateMachine(ArrayBuilder<BoundStatement> bodyBuilder, NamedTypeSymbol frameType, LocalSymbol stateMachineLocal); /// <summary> /// Generate implementation-specific state machine initialization for the kickoff method body. /// </summary> protected abstract BoundStatement GenerateStateMachineCreation(LocalSymbol stateMachineVariable, NamedTypeSymbol frameType, IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies); /// <summary> /// Generate implementation-specific state machine member method implementations. /// </summary> protected abstract void GenerateMethodImplementations(); protected BoundStatement Rewrite() { if (this.body.HasErrors) { return this.body; } F.OpenNestedType(stateMachineType); GenerateControlFields(); if (PreserveInitialParameterValuesAndThreadId && CanGetThreadId()) { // if it is an enumerable or async-enumerable, and either Environment.CurrentManagedThreadId or Thread.ManagedThreadId are available // add a field: int initialThreadId initialThreadIdField = F.StateMachineField(F.SpecialType(SpecialType.System_Int32), GeneratedNames.MakeIteratorCurrentThreadIdFieldName()); } // fields for the initial values of all the parameters of the method if (PreserveInitialParameterValuesAndThreadId) { initialParameters = new Dictionary<Symbol, CapturedSymbolReplacement>(); } // fields for the captured variables of the method var variablesToHoist = IteratorAndAsyncCaptureWalker.Analyze(F.Compilation, method, body, diagnostics.DiagnosticBag); if (diagnostics.HasAnyErrors()) { // Avoid triggering assertions in further lowering. return new BoundBadStatement(F.Syntax, ImmutableArray<BoundNode>.Empty, hasErrors: true); } CreateNonReusableLocalProxies(variablesToHoist, out this.nonReusableLocalProxies, out this.nextFreeHoistedLocalSlot); this.hoistedVariables = variablesToHoist; GenerateMethodImplementations(); // Return a replacement body for the kickoff method return GenerateKickoffMethodBody(); } private void CreateNonReusableLocalProxies( IEnumerable<Symbol> variablesToHoist, out IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies, out int nextFreeHoistedLocalSlot) { var proxiesBuilder = new Dictionary<Symbol, CapturedSymbolReplacement>(); var typeMap = stateMachineType.TypeMap; bool isDebugBuild = F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug; bool mapToPreviousFields = isDebugBuild && slotAllocatorOpt != null; nextFreeHoistedLocalSlot = mapToPreviousFields ? slotAllocatorOpt.PreviousHoistedLocalSlotCount : 0; foreach (var variable in variablesToHoist) { Debug.Assert(variable.Kind == SymbolKind.Local || variable.Kind == SymbolKind.Parameter); if (variable.Kind == SymbolKind.Local) { var local = (LocalSymbol)variable; var synthesizedKind = local.SynthesizedKind; if (!synthesizedKind.MustSurviveStateMachineSuspension()) { continue; } // no need to hoist constants if (local.IsConst) { continue; } if (local.RefKind != RefKind.None) { // we'll create proxies for these variables later: Debug.Assert(synthesizedKind == SynthesizedLocalKind.Spill); continue; } Debug.Assert(local.RefKind == RefKind.None); StateMachineFieldSymbol field = null; if (ShouldPreallocateNonReusableProxy(local)) { // variable needs to be hoisted var fieldType = typeMap.SubstituteType(local.Type).Type; LocalDebugId id; int slotIndex = -1; if (isDebugBuild) { // Calculate local debug id. // // EnC: When emitting the baseline (gen 0) the id is stored in a custom debug information attached to the kickoff method. // When emitting a delta the id is only used to map to the existing field in the previous generation. SyntaxNode declaratorSyntax = local.GetDeclaratorSyntax(); int syntaxOffset = method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(declaratorSyntax), declaratorSyntax.SyntaxTree); int ordinal = synthesizedLocalOrdinals.AssignLocalOrdinal(synthesizedKind, syntaxOffset); id = new LocalDebugId(syntaxOffset, ordinal); // map local id to the previous id, if available: int previousSlotIndex; if (mapToPreviousFields && slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex( declaratorSyntax, F.ModuleBuilderOpt.Translate(fieldType, declaratorSyntax, diagnostics.DiagnosticBag), synthesizedKind, id, diagnostics.DiagnosticBag, out previousSlotIndex)) { slotIndex = previousSlotIndex; } } else { id = LocalDebugId.None; } if (slotIndex == -1) { slotIndex = nextFreeHoistedLocalSlot++; } string fieldName = GeneratedNames.MakeHoistedLocalFieldName(synthesizedKind, slotIndex, local.Name); field = F.StateMachineField(fieldType, fieldName, new LocalSlotDebugInfo(synthesizedKind, id), slotIndex); } if (field != null) { proxiesBuilder.Add(local, new CapturedToStateMachineFieldReplacement(field, isReusable: false)); } } else { var parameter = (ParameterSymbol)variable; if (parameter.IsThis) { var containingType = method.ContainingType; var proxyField = F.StateMachineField(containingType, GeneratedNames.ThisProxyFieldName(), isPublic: true, isThis: true); proxiesBuilder.Add(parameter, new CapturedToStateMachineFieldReplacement(proxyField, isReusable: false)); if (PreserveInitialParameterValuesAndThreadId) { var initialThis = containingType.IsStructType() ? F.StateMachineField(containingType, GeneratedNames.StateMachineThisParameterProxyName(), isPublic: true, isThis: true) : proxyField; initialParameters.Add(parameter, new CapturedToStateMachineFieldReplacement(initialThis, isReusable: false)); } } else { // The field needs to be public iff it is initialized directly from the kickoff method // (i.e. not for IEnumerable which loads the values from parameter proxies). var proxyField = F.StateMachineField(typeMap.SubstituteType(parameter.Type).Type, parameter.Name, isPublic: !PreserveInitialParameterValuesAndThreadId); proxiesBuilder.Add(parameter, new CapturedToStateMachineFieldReplacement(proxyField, isReusable: false)); if (PreserveInitialParameterValuesAndThreadId) { var field = F.StateMachineField(typeMap.SubstituteType(parameter.Type).Type, GeneratedNames.StateMachineParameterProxyFieldName(parameter.Name), isPublic: true); initialParameters.Add(parameter, new CapturedToStateMachineFieldReplacement(field, isReusable: false)); } } } } proxies = proxiesBuilder; } private bool ShouldPreallocateNonReusableProxy(LocalSymbol local) { var synthesizedKind = local.SynthesizedKind; var optimizationLevel = F.Compilation.Options.OptimizationLevel; // do not preallocate proxy fields for user defined locals in release // otherwise we will be allocating fields for all locals even when fields can be reused // see https://github.com/dotnet/roslyn/issues/15290 if (optimizationLevel == OptimizationLevel.Release && synthesizedKind == SynthesizedLocalKind.UserDefined) { return false; } return !synthesizedKind.IsSlotReusable(optimizationLevel); } private BoundStatement GenerateKickoffMethodBody() { F.CurrentFunction = method; var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var frameType = method.IsGenericMethod ? stateMachineType.Construct(method.TypeArgumentsWithAnnotations, unbound: false) : stateMachineType; LocalSymbol stateMachineVariable = F.SynthesizedLocal(frameType, null); InitializeStateMachine(bodyBuilder, frameType, stateMachineVariable); // plus code to initialize all of the parameter proxies result.proxy var proxies = PreserveInitialParameterValuesAndThreadId ? initialParameters : nonReusableLocalProxies; bodyBuilder.Add(GenerateStateMachineCreation(stateMachineVariable, frameType, proxies)); return F.Block( ImmutableArray.Create(stateMachineVariable), bodyBuilder.ToImmutableAndFree()); } protected BoundStatement GenerateParameterStorage(LocalSymbol stateMachineVariable, IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> proxies) { var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // starting with the "this" proxy if (!method.IsStatic) { Debug.Assert((object)method.ThisParameter != null); CapturedSymbolReplacement proxy; if (proxies.TryGetValue(method.ThisParameter, out proxy)) { bodyBuilder.Add(F.Assignment(proxy.Replacement(F.Syntax, frameType1 => F.Local(stateMachineVariable)), F.This())); } } foreach (var parameter in method.Parameters) { CapturedSymbolReplacement proxy; if (proxies.TryGetValue(parameter, out proxy)) { bodyBuilder.Add(F.Assignment(proxy.Replacement(F.Syntax, frameType1 => F.Local(stateMachineVariable)), F.Parameter(parameter))); } } return F.Block(bodyBuilder.ToImmutableAndFree()); } protected SynthesizedImplementationMethod OpenMethodImplementation( MethodSymbol methodToImplement, string methodName = null, bool hasMethodBodyDependency = false) { var result = new SynthesizedStateMachineDebuggerHiddenMethod(methodName, methodToImplement, (StateMachineTypeSymbol)F.CurrentType, null, hasMethodBodyDependency); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, result.GetCciAdapter()); F.CurrentFunction = result; return result; } protected MethodSymbol OpenPropertyImplementation(MethodSymbol getterToImplement) { var prop = new SynthesizedStateMachineProperty(getterToImplement, (StateMachineTypeSymbol)F.CurrentType); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, prop.GetCciAdapter()); var getter = prop.GetMethod; F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, getter.GetCciAdapter()); F.CurrentFunction = getter; return getter; } protected SynthesizedImplementationMethod OpenMoveNextMethodImplementation(MethodSymbol methodToImplement) { var result = new SynthesizedStateMachineMoveNextMethod(methodToImplement, (StateMachineTypeSymbol)F.CurrentType); F.ModuleBuilderOpt.AddSynthesizedDefinition(F.CurrentType, result.GetCciAdapter()); F.CurrentFunction = result; return result; } /// <summary> /// Produce Environment.CurrentManagedThreadId if available, otherwise CurrentThread.ManagedThreadId /// </summary> protected BoundExpression MakeCurrentThreadId() { Debug.Assert(CanGetThreadId()); // .NET Core has removed the Thread class. We can get the managed thread id by making a call to // Environment.CurrentManagedThreadId. If that method is not present (pre 4.5) fall back to the old behavior. var currentManagedThreadIdProperty = (PropertySymbol)F.WellKnownMember(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional: true); if ((object)currentManagedThreadIdProperty != null) { MethodSymbol currentManagedThreadIdMethod = currentManagedThreadIdProperty.GetMethod; if ((object)currentManagedThreadIdMethod != null) { return F.Call(null, currentManagedThreadIdMethod); } } return F.Property(F.Property(WellKnownMember.System_Threading_Thread__CurrentThread), WellKnownMember.System_Threading_Thread__ManagedThreadId); } /// <summary> /// Generate the GetEnumerator() method for iterators and GetAsyncEnumerator() for async-iterators. /// </summary> protected SynthesizedImplementationMethod GenerateIteratorGetEnumerator(MethodSymbol getEnumeratorMethod, ref BoundExpression managedThreadId, int initialState) { // Produces: // {StateMachineType} result; // if (this.initialThreadId == {managedThreadId} && this.state == -2) // { // this.state = {initialState}; // extraReset // result = this; // } // else // { // result = new {StateMachineType}({initialState}); // } // // result.parameter = this.parameterProxy; // OR more complex initialization for async-iterator parameter marked with [EnumeratorCancellation] // The implementation doesn't depend on the method body of the iterator method. // Only on its parameters and staticness. var getEnumerator = OpenMethodImplementation( getEnumeratorMethod, hasMethodBodyDependency: false); var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // {StateMachineType} result; var resultVariable = F.SynthesizedLocal(stateMachineType, null); // result = new {StateMachineType}({initialState}) BoundStatement makeIterator = F.Assignment(F.Local(resultVariable), F.New(stateMachineType.Constructor, F.Literal(initialState))); var thisInitialized = F.GenerateLabel("thisInitialized"); if ((object)initialThreadIdField != null) { managedThreadId = MakeCurrentThreadId(); var thenBuilder = ArrayBuilder<BoundStatement>.GetInstance(4); GenerateResetInstance(thenBuilder, initialState); thenBuilder.Add( // result = this; F.Assignment(F.Local(resultVariable), F.This())); if (method.IsStatic || method.ThisParameter.Type.IsReferenceType) { // if this is a reference type, no need to copy it since it is not assignable thenBuilder.Add( // goto thisInitialized; F.Goto(thisInitialized)); } makeIterator = F.If( // if (this.state == -2 && this.initialThreadId == Thread.CurrentThread.ManagedThreadId) condition: F.LogicalAnd( F.IntEqual(F.Field(F.This(), stateField), F.Literal(StateMachineStates.FinishedStateMachine)), F.IntEqual(F.Field(F.This(), initialThreadIdField), managedThreadId)), thenClause: F.Block(thenBuilder.ToImmutableAndFree()), elseClauseOpt: makeIterator); } bodyBuilder.Add(makeIterator); // Initialize all the parameter copies var copySrc = initialParameters; var copyDest = nonReusableLocalProxies; if (!method.IsStatic) { // starting with "this" CapturedSymbolReplacement proxy; if (copyDest.TryGetValue(method.ThisParameter, out proxy)) { bodyBuilder.Add( F.Assignment( proxy.Replacement(F.Syntax, stateMachineType => F.Local(resultVariable)), copySrc[method.ThisParameter].Replacement(F.Syntax, stateMachineType => F.This()))); } } bodyBuilder.Add(F.Label(thisInitialized)); foreach (var parameter in method.Parameters) { CapturedSymbolReplacement proxy; if (copyDest.TryGetValue(parameter, out proxy)) { // result.parameter BoundExpression resultParameter = proxy.Replacement(F.Syntax, stateMachineType => F.Local(resultVariable)); // this.parameterProxy BoundExpression parameterProxy = copySrc[parameter].Replacement(F.Syntax, stateMachineType => F.This()); BoundStatement copy = InitializeParameterField(getEnumeratorMethod, parameter, resultParameter, parameterProxy); bodyBuilder.Add(copy); } } bodyBuilder.Add(F.Return(F.Local(resultVariable))); F.CloseMethod(F.Block(ImmutableArray.Create(resultVariable), bodyBuilder.ToImmutableAndFree())); return getEnumerator; } /// <summary> /// Generate logic to reset the current instance (rather than creating a new instance) /// </summary> protected virtual void GenerateResetInstance(ArrayBuilder<BoundStatement> builder, int initialState) { builder.Add( // this.state = {initialState}; F.Assignment(F.Field(F.This(), stateField), F.Literal(initialState))); } protected virtual BoundStatement InitializeParameterField(MethodSymbol getEnumeratorMethod, ParameterSymbol parameter, BoundExpression resultParameter, BoundExpression parameterProxy) { Debug.Assert(!method.IsIterator || !method.IsAsync); // an override handles async-iterators // result.parameter = this.parameterProxy; return F.Assignment(resultParameter, parameterProxy); } /// <summary> /// Returns true if either Thread.ManagedThreadId or Environment.CurrentManagedThreadId are available /// </summary> protected bool CanGetThreadId() { return (object)F.WellKnownMember(WellKnownMember.System_Threading_Thread__ManagedThreadId, isOptional: true) != null || (object)F.WellKnownMember(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional: true) != null; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { internal sealed class InteractiveDocumentNavigationService : IDocumentNavigationService { private readonly IThreadingContext _threadingContext; public InteractiveDocumentNavigationService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // This switch is technically not needed as the call to CanNavigateToSpan just returns 'true'. // However, this abides by the contract that CanNavigateToSpan only be called on the UI thread. // It also means if we ever update that method, this code will stay corrrect. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { if (workspace is not InteractiveWindowWorkspace interactiveWorkspace) { Debug.Fail("InteractiveDocumentNavigationService called with incorrect workspace!"); return false; } var textView = interactiveWorkspace.Window.TextView; var document = interactiveWorkspace.CurrentSolution.GetDocument(documentId); var textSnapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { return false; } var snapshotSpan = new SnapshotSpan(textSnapshot, textSpan.Start, textSpan.Length); var virtualSnapshotSpan = new VirtualSnapshotSpan(snapshotSpan); if (!textView.TryGetSurfaceBufferSpan(virtualSnapshotSpan, out var surfaceBufferSpan)) { return false; } textView.Selection.Select(surfaceBufferSpan.Start, surfaceBufferSpan.End); textView.ViewScroller.EnsureSpanVisible(surfaceBufferSpan.SnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); // Moving the caret must be the last operation involving surfaceBufferSpan because // it might update the version number of textView.TextSnapshot (VB does line commit // when the caret leaves a line which might cause pretty listing), which must be // equal to surfaceBufferSpan.SnapshotSpan.Snapshot's version number. textView.Caret.MoveTo(surfaceBufferSpan.Start); textView.VisualElement.Focus(); return true; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { internal sealed class InteractiveDocumentNavigationService : IDocumentNavigationService { private readonly IThreadingContext _threadingContext; public InteractiveDocumentNavigationService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // This switch is technically not needed as the call to CanNavigateToSpan just returns 'true'. // However, this abides by the contract that CanNavigateToSpan only be called on the UI thread. // It also means if we ever update that method, this code will stay corrrect. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { if (workspace is not InteractiveWindowWorkspace interactiveWorkspace) { Debug.Fail("InteractiveDocumentNavigationService called with incorrect workspace!"); return false; } if (interactiveWorkspace.Window is null) { Debug.Fail("We are trying to navigate with a workspace that doesn't have a window!"); return false; } var textView = interactiveWorkspace.Window.TextView; var document = interactiveWorkspace.CurrentSolution.GetDocument(documentId); var textSnapshot = document?.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { return false; } var snapshotSpan = new SnapshotSpan(textSnapshot, textSpan.Start, textSpan.Length); var virtualSnapshotSpan = new VirtualSnapshotSpan(snapshotSpan); if (!textView.TryGetSurfaceBufferSpan(virtualSnapshotSpan, out var surfaceBufferSpan)) { return false; } textView.Selection.Select(surfaceBufferSpan.Start, surfaceBufferSpan.End); textView.ViewScroller.EnsureSpanVisible(surfaceBufferSpan.SnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); // Moving the caret must be the last operation involving surfaceBufferSpan because // it might update the version number of textView.TextSnapshot (VB does line commit // when the caret leaves a line which might cause pretty listing), which must be // equal to surfaceBufferSpan.SnapshotSpan.Snapshot's version number. textView.Caret.MoveTo(surfaceBufferSpan.Start); textView.VisualElement.Focus(); return true; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => throw new NotSupportedException(); } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem; namespace Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar { internal abstract class AbstractEditorNavigationBarItemService : ForegroundThreadAffinitizedObject, INavigationBarItemService { protected AbstractEditorNavigationBarItemService(IThreadingContext threadingContext) : base(threadingContext, assertIsForeground: false) { } protected abstract Task<bool> TryNavigateToItemAsync(Document document, WrappedNavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken); public async Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<CodeAnalysis.NavigationBar.INavigationBarItemService>(); var workspaceSupportsDocumentChanges = document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument); var items = await service.GetItemsAsync(document, workspaceSupportsDocumentChanges, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(v => (NavigationBarItem)new WrappedNavigationBarItem(textVersion, v)); } public Task<bool> TryNavigateToItemAsync(Document document, NavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken) => TryNavigateToItemAsync(document, (WrappedNavigationBarItem)item, textView, textVersion, cancellationToken); protected async Task NavigateToSymbolItemAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, ITextVersion textVersion, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var (documentId, position, virtualSpace) = await GetNavigationLocationAsync( document, item, symbolItem, textVersion, cancellationToken).ConfigureAwait(false); // Ensure we're back on the UI thread before either navigating or showing a failure message. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); NavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } protected void NavigateToPosition(Workspace workspace, DocumentId? documentId, int position, int virtualSpace, CancellationToken cancellationToken) { this.AssertIsForeground(); var navigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); if (navigationService.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken)) { navigationService.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options: null, cancellationToken); } else { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification(EditorFeaturesResources.The_definition_of_the_object_is_hidden, severity: NotificationSeverity.Error); } } internal virtual Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, ITextVersion textVersion, CancellationToken cancellationToken) { // If the item points to a location in this document, then just determine the current location // of that item and go directly to it. var navigationSpan = item.TryGetNavigationSpan(textVersion); if (navigationSpan != null) { return Task.FromResult((document.Id, navigationSpan.Value.Start, 0)); } else { // Otherwise, the item pointed to a location in another document. Just return the position we // computed and stored for it. Contract.ThrowIfNull(symbolItem.Location.OtherDocumentInfo); var (documentId, span) = symbolItem.Location.OtherDocumentInfo.Value; return Task.FromResult((documentId, span.Start, 0)); } } public bool ShowItemGrayedIfNear(NavigationBarItem item) { // We only show items in gray when near that actually exist (i.e. are not meant for codegen). // This will be all C# items, and only VB non-codegen items. return ((WrappedNavigationBarItem)item).UnderlyingItem is SymbolItem; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem; namespace Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar { internal abstract class AbstractEditorNavigationBarItemService : ForegroundThreadAffinitizedObject, INavigationBarItemService { protected AbstractEditorNavigationBarItemService(IThreadingContext threadingContext) : base(threadingContext, assertIsForeground: false) { } protected abstract Task<bool> TryNavigateToItemAsync(Document document, WrappedNavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken); public async Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<CodeAnalysis.NavigationBar.INavigationBarItemService>(); var workspaceSupportsDocumentChanges = document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument); var items = await service.GetItemsAsync(document, workspaceSupportsDocumentChanges, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(v => (NavigationBarItem)new WrappedNavigationBarItem(textVersion, v)); } public Task<bool> TryNavigateToItemAsync(Document document, NavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken) => TryNavigateToItemAsync(document, (WrappedNavigationBarItem)item, textView, textVersion, cancellationToken); protected async Task NavigateToSymbolItemAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, ITextVersion textVersion, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var (documentId, position, virtualSpace) = await GetNavigationLocationAsync( document, item, symbolItem, textVersion, cancellationToken).ConfigureAwait(false); // Ensure we're back on the UI thread before either navigating or showing a failure message. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); NavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } protected void NavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { this.AssertIsForeground(); var navigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); if (navigationService.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken)) { navigationService.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options: null, cancellationToken); } else { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification(EditorFeaturesResources.The_definition_of_the_object_is_hidden, severity: NotificationSeverity.Error); } } internal virtual Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, ITextVersion textVersion, CancellationToken cancellationToken) { // If the item points to a location in this document, then just determine the current location // of that item and go directly to it. var navigationSpan = item.TryGetNavigationSpan(textVersion); if (navigationSpan != null) { return Task.FromResult((document.Id, navigationSpan.Value.Start, 0)); } else { // Otherwise, the item pointed to a location in another document. Just return the position we // computed and stored for it. Contract.ThrowIfNull(symbolItem.Location.OtherDocumentInfo); var (documentId, span) = symbolItem.Location.OtherDocumentInfo.Value; return Task.FromResult((documentId, span.Start, 0)); } } public bool ShowItemGrayedIfNear(NavigationBarItem item) { // We only show items in gray when near that actually exist (i.e. are not meant for codegen). // This will be all C# items, and only VB non-codegen items. return ((WrappedNavigationBarItem)item).UnderlyingItem is SymbolItem; } } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/Navigation/DefaultDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Navigation { internal sealed class DefaultDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => false; public Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => SpecializedTasks.False; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) => false; public Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) => SpecializedTasks.False; public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => false; public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Navigation { internal sealed class DefaultDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => false; public Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => SpecializedTasks.False; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) => false; public Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) => SpecializedTasks.False; public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) => false; public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => false; } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Legal to call from any thread.</remarks> Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { /// <remarks>Only legal to call on the UI thread.</remarks> public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Legal to call from any thread.</remarks> public static Task<bool> TryNavigateToSpanAsync(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpanAsync(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> /// <remarks>Legal to call from any thread.</remarks> Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> /// <remarks>Only legal to call on the UI thread.</remarks> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { /// <remarks>Only legal to call on the UI thread.</remarks> public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Legal to call from any thread.</remarks> public static Task<bool> TryNavigateToSpanAsync(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, CancellationToken cancellationToken) => service.TryNavigateToSpanAsync(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); /// <remarks>Only legal to call on the UI thread.</remarks> public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceService(typeof(IDocumentNavigationService), ServiceLayer.Host), Shared] [Export(typeof(VisualStudioDocumentNavigationService))] internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsRunningDocumentTable4 _runningDocumentTable; private readonly IThreadingContext _threadingContext; private readonly Lazy<SourceGeneratedFileManager> _sourceGeneratedFileManager; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentNavigationService( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Lazy<SourceGeneratedFileManager> sourceGeneratedFileManager /* lazy to avoid circularities */) : base(threadingContext) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); _threadingContext = threadingContext; _sourceGeneratedFileManager = sourceGeneratedFileManager; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, _ => textSpan, text => GetVsTextSpan(text, textSpan, allowInvalidSpan), options, cancellationToken); static VsTextSpan GetVsTextSpan(SourceText text, TextSpan textSpan, bool allowInvalidSpan) { var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan && !allowInvalidSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForSpan(boundedTextSpan); } } public bool TryNavigateToLineAndOffset( Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromLineAndOffset(document, lineNumber, offset, cancellationToken), text => GetVsTextSpan(text, lineNumber, offset), options, cancellationToken); static TextSpan GetTextSpanFromLineAndOffset(Document document, int lineNumber, int offset, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int lineNumber, int offset) { return text.GetVsTextSpanForLineOffset(lineNumber, offset); } } public bool TryNavigateToPosition( Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromPosition(document, position, virtualSpace, cancellationToken), text => GetVsTextSpan(text, position, virtualSpace), options, cancellationToken); static TextSpan GetTextSpanFromPosition(Document document, int position, int virtualSpace, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); text.GetLineAndOffset(position, out var lineNumber, out var offset); offset += virtualSpace; var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int position, int virtualSpace) { var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForPosition(boundedPosition, virtualSpace); } } private bool TryNavigateToLocation( Workspace workspace, DocumentId documentId, Func<Document, TextSpan> getTextSpanForMapping, Func<SourceText, VsTextSpan> getVsTextSpan, OptionSet options, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var solution = workspace.CurrentSolution; using (OpenNewDocumentStateScope(options ?? solution.Options)) { if (solution.GetDocument(documentId) == null) { var project = solution.GetProject(documentId.ProjectId); if (project is null) { // This is a source generated document shown in Solution Explorer, but is no longer valid since // the configuration and/or platform changed since the last generation completed. return false; } var generatedDocument = project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).AsTask().GetAwaiter().GetResult(); if (generatedDocument != null) { _sourceGeneratedFileManager.Value.NavigateToSourceGeneratedFile(generatedDocument, getTextSpanForMapping(generatedDocument), cancellationToken); return true; } } // Before attempting to open the document, check if the location maps to a different file that should be opened instead. var document = solution.GetDocument(documentId); var spanMappingService = document?.Services.GetService<ISpanMappingService>(); if (spanMappingService != null) { var mappedSpan = GetMappedSpan(spanMappingService, document, getTextSpanForMapping(document), cancellationToken); if (mappedSpan.HasValue) { // Check if the mapped file matches one already in the workspace. // If so use the workspace APIs to navigate to it. Otherwise use VS APIs to navigate to the file path. var documentIdsForFilePath = solution.GetDocumentIdsWithFilePath(mappedSpan.Value.FilePath); if (!documentIdsForFilePath.IsEmpty) { // If the mapped file maps to the same document that was passed in, then re-use the documentId to preserve context. // Otherwise, just pick one of the ids to use for navigation. var documentIdToNavigate = documentIdsForFilePath.Contains(documentId) ? documentId : documentIdsForFilePath.First(); return NavigateToFileInWorkspace(documentIdToNavigate, workspace, getVsTextSpan, cancellationToken); } return TryNavigateToMappedFile(workspace, document, mappedSpan.Value, cancellationToken); } } return NavigateToFileInWorkspace(documentId, workspace, getVsTextSpan, cancellationToken); } } private bool NavigateToFileInWorkspace( DocumentId documentId, Workspace workspace, Func<SourceText, VsTextSpan> getVsTextSpan, CancellationToken cancellationToken) { var document = OpenDocument(workspace, documentId); if (document == null) { return false; } var text = document.GetTextSynchronously(cancellationToken); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = getVsTextSpan(text); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } private bool TryNavigateToMappedFile(Workspace workspace, Document generatedDocument, MappedSpanResult mappedSpanResult, CancellationToken cancellationToken) { var vsWorkspace = (VisualStudioWorkspaceImpl)workspace; // TODO - Move to IOpenDocumentService - https://github.com/dotnet/roslyn/issues/45954 // Pass the original result's project context so that if the mapped file has the same context available, we navigate // to the mapped file with a consistent project context. vsWorkspace.OpenDocumentFromPath(mappedSpanResult.FilePath, generatedDocument.Project.Id); if (_runningDocumentTable.TryGetBufferFromMoniker(_editorAdaptersFactoryService, mappedSpanResult.FilePath, out var textBuffer)) { var vsTextSpan = new VsTextSpan { iStartIndex = mappedSpanResult.LinePositionSpan.Start.Character, iStartLine = mappedSpanResult.LinePositionSpan.Start.Line, iEndIndex = mappedSpanResult.LinePositionSpan.End.Character, iEndLine = mappedSpanResult.LinePositionSpan.End.Line }; return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } return false; } private MappedSpanResult? GetMappedSpan(ISpanMappingService spanMappingService, Document generatedDocument, TextSpan textSpan, CancellationToken cancellationToken) { // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var results = _threadingContext.JoinableTaskFactory.Run(() => spanMappingService.MapSpansAsync(generatedDocument, SpecializedCollections.SingletonEnumerable(textSpan), cancellationToken)); if (!results.IsDefaultOrEmpty) { return results.First(); } return null; } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a position that is not /// inside the bounds of the associated <see cref="Document"/>. This method returns a /// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the /// returned position is different from the given position, then the worst observable /// behavior is either no navigation or navigation to the end of the document. See the /// following bugs for more details: /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409 /// </summary> private static int GetPositionWithinDocumentBounds(int position, int documentLength) => Math.Min(documentLength, Math.Max(position, 0)); /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/> /// that is not inside the bounds of the associated <see cref="Document"/>. This method /// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If /// the returned span is different from the given span, then the worst observable behavior /// is either no navigation or navigation to the end of the document. /// See https://github.com/dotnet/roslyn/issues/7660 for more details. /// </summary> private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength) => TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength)); private static Document OpenDocument(Workspace workspace, DocumentId documentId) { // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { workspace.OpenDocument(documentId); } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } public bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, cancellationToken)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private static bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } return true; } private static bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) => spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out _); private static IDisposable OpenNewDocumentStateScope(OptionSet options) { var state = options.GetOption(NavigationOptions.PreferProvisionalTab) ? __VSNEWDOCUMENTSTATE.NDS_Provisional : __VSNEWDOCUMENTSTATE.NDS_Permanent; if (!options.GetOption(NavigationOptions.ActivateTab)) { state |= __VSNEWDOCUMENTSTATE.NDS_NoActivate; } return new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceService(typeof(IDocumentNavigationService), ServiceLayer.Host), Shared] [Export(typeof(VisualStudioDocumentNavigationService))] internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IVsRunningDocumentTable4 _runningDocumentTable; private readonly IThreadingContext _threadingContext; private readonly Lazy<SourceGeneratedFileManager> _sourceGeneratedFileManager; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentNavigationService( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Lazy<SourceGeneratedFileManager> sourceGeneratedFileManager /* lazy to avoid circularities */) : base(threadingContext) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable)); _threadingContext = threadingContext; _sourceGeneratedFileManager = sourceGeneratedFileManager; } public async Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetRequiredDocument(documentId); var text = document.GetTextSynchronously(cancellationToken); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public async Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, _ => textSpan, text => GetVsTextSpan(text, textSpan, allowInvalidSpan), options, cancellationToken); static VsTextSpan GetVsTextSpan(SourceText text, TextSpan textSpan, bool allowInvalidSpan) { var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan && !allowInvalidSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForSpan(boundedTextSpan); } } public bool TryNavigateToLineAndOffset( Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromLineAndOffset(document, lineNumber, offset, cancellationToken), text => GetVsTextSpan(text, lineNumber, offset), options, cancellationToken); static TextSpan GetTextSpanFromLineAndOffset(Document document, int lineNumber, int offset, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int lineNumber, int offset) { return text.GetVsTextSpanForLineOffset(lineNumber, offset); } } public bool TryNavigateToPosition( Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) { return TryNavigateToLocation(workspace, documentId, document => GetTextSpanFromPosition(document, position, virtualSpace, cancellationToken), text => GetVsTextSpan(text, position, virtualSpace), options, cancellationToken); static TextSpan GetTextSpanFromPosition(Document document, int position, int virtualSpace, CancellationToken cancellationToken) { var text = document.GetTextSynchronously(cancellationToken); text.GetLineAndOffset(position, out var lineNumber, out var offset); offset += virtualSpace; var linePosition = new LinePosition(lineNumber, offset); return text.Lines.GetTextSpan(new LinePositionSpan(linePosition, linePosition)); } static VsTextSpan GetVsTextSpan(SourceText text, int position, int virtualSpace) { var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportAndCatch(e)) { } } return text.GetVsTextSpanForPosition(boundedPosition, virtualSpace); } } private bool TryNavigateToLocation( Workspace workspace, DocumentId documentId, Func<Document, TextSpan> getTextSpanForMapping, Func<SourceText, VsTextSpan> getVsTextSpan, OptionSet? options, CancellationToken cancellationToken) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var solution = workspace.CurrentSolution; using (OpenNewDocumentStateScope(options ?? solution.Options)) { var document = solution.GetDocument(documentId); if (document == null) { var project = solution.GetProject(documentId.ProjectId); if (project is null) { // This is a source generated document shown in Solution Explorer, but is no longer valid since // the configuration and/or platform changed since the last generation completed. return false; } var generatedDocument = project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).AsTask().GetAwaiter().GetResult(); if (generatedDocument != null) { _sourceGeneratedFileManager.Value.NavigateToSourceGeneratedFile(generatedDocument, getTextSpanForMapping(generatedDocument), cancellationToken); return true; } return false; } // Before attempting to open the document, check if the location maps to a different file that should be opened instead. var spanMappingService = document.Services.GetService<ISpanMappingService>(); if (spanMappingService != null) { var mappedSpan = GetMappedSpan(spanMappingService, document, getTextSpanForMapping(document), cancellationToken); if (mappedSpan.HasValue) { // Check if the mapped file matches one already in the workspace. // If so use the workspace APIs to navigate to it. Otherwise use VS APIs to navigate to the file path. var documentIdsForFilePath = solution.GetDocumentIdsWithFilePath(mappedSpan.Value.FilePath); if (!documentIdsForFilePath.IsEmpty) { // If the mapped file maps to the same document that was passed in, then re-use the documentId to preserve context. // Otherwise, just pick one of the ids to use for navigation. var documentIdToNavigate = documentIdsForFilePath.Contains(documentId) ? documentId : documentIdsForFilePath.First(); return NavigateToFileInWorkspace(documentIdToNavigate, workspace, getVsTextSpan, cancellationToken); } return TryNavigateToMappedFile(workspace, document, mappedSpan.Value, cancellationToken); } } return NavigateToFileInWorkspace(documentId, workspace, getVsTextSpan, cancellationToken); } } private bool NavigateToFileInWorkspace( DocumentId documentId, Workspace workspace, Func<SourceText, VsTextSpan> getVsTextSpan, CancellationToken cancellationToken) { var document = OpenDocument(workspace, documentId); if (document == null) { return false; } var text = document.GetTextSynchronously(cancellationToken); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = getVsTextSpan(text); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } private bool TryNavigateToMappedFile(Workspace workspace, Document generatedDocument, MappedSpanResult mappedSpanResult, CancellationToken cancellationToken) { var vsWorkspace = (VisualStudioWorkspaceImpl)workspace; // TODO - Move to IOpenDocumentService - https://github.com/dotnet/roslyn/issues/45954 // Pass the original result's project context so that if the mapped file has the same context available, we navigate // to the mapped file with a consistent project context. vsWorkspace.OpenDocumentFromPath(mappedSpanResult.FilePath, generatedDocument.Project.Id); if (_runningDocumentTable.TryGetBufferFromMoniker(_editorAdaptersFactoryService, mappedSpanResult.FilePath, out var textBuffer)) { var vsTextSpan = new VsTextSpan { iStartIndex = mappedSpanResult.LinePositionSpan.Start.Character, iStartLine = mappedSpanResult.LinePositionSpan.Start.Line, iEndIndex = mappedSpanResult.LinePositionSpan.End.Character, iEndLine = mappedSpanResult.LinePositionSpan.End.Line }; return NavigateTo(textBuffer, vsTextSpan, cancellationToken); } return false; } private MappedSpanResult? GetMappedSpan(ISpanMappingService spanMappingService, Document generatedDocument, TextSpan textSpan, CancellationToken cancellationToken) { // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var results = _threadingContext.JoinableTaskFactory.Run(() => spanMappingService.MapSpansAsync(generatedDocument, SpecializedCollections.SingletonEnumerable(textSpan), cancellationToken)); if (!results.IsDefaultOrEmpty) { return results.First(); } return null; } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a position that is not /// inside the bounds of the associated <see cref="Document"/>. This method returns a /// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the /// returned position is different from the given position, then the worst observable /// behavior is either no navigation or navigation to the end of the document. See the /// following bugs for more details: /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409 /// </summary> private static int GetPositionWithinDocumentBounds(int position, int documentLength) => Math.Min(documentLength, Math.Max(position, 0)); /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/> /// that is not inside the bounds of the associated <see cref="Document"/>. This method /// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If /// the returned span is different from the given span, then the worst observable behavior /// is either no navigation or navigation to the end of the document. /// See https://github.com/dotnet/roslyn/issues/7660 for more details. /// </summary> private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength) => TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength)); private static Document? OpenDocument(Workspace workspace, DocumentId documentId) { // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { workspace.OpenDocument(documentId); } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } public bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, cancellationToken)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private static bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } return true; } private static bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) => spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out _); private static IDisposable OpenNewDocumentStateScope(OptionSet options) { var state = options.GetOption(NavigationOptions.PreferProvisionalTab) ? __VSNEWDOCUMENTSTATE.NDS_Provisional : __VSNEWDOCUMENTSTATE.NDS_Permanent; if (!options.GetOption(NavigationOptions.ActivateTab)) { state |= __VSNEWDOCUMENTSTATE.NDS_NoActivate; } return new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation); } } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { using Workspace = CodeAnalysis.Workspace; [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal class MockDocumentNavigationServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDocumentNavigationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return new MockDocumentNavigationService(); } private class MockDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => true; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => true; public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => SpecializedTasks.True; public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => true; public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => true; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpans, CancellationToken cancellationToken) => true; public Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken) => SpecializedTasks.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { using Workspace = CodeAnalysis.Workspace; [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal class MockDocumentNavigationServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDocumentNavigationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return new MockDocumentNavigationService(); } private class MockDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => true; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => true; public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public Task<bool> CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => SpecializedTasks.True; public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet? options, CancellationToken cancellationToken) => true; public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => true; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpans, CancellationToken cancellationToken) => true; public Task<bool> TryNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet? options, bool allowInvalidSpan, CancellationToken cancellationToken) => SpecializedTasks.True; } } }
1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.Walker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Operations walker used for walking high-level operation tree /// as well as control flow graph based operations. /// </summary> private sealed class Walker : OperationWalker { private AnalysisData _currentAnalysisData; private ISymbol _currentContainingSymbol; private IOperation _currentRootOperation; private CancellationToken _cancellationToken; private PooledDictionary<IAssignmentOperation, PooledHashSet<(ISymbol, IOperation)>> _pendingWritesMap; private static readonly ObjectPool<Walker> s_visitorPool = new(() => new Walker()); private Walker() { } public static void AnalyzeOperationsAndUpdateData( ISymbol containingSymbol, IEnumerable<IOperation> operations, AnalysisData analysisData, CancellationToken cancellationToken) { var visitor = s_visitorPool.Allocate(); try { visitor.Visit(containingSymbol, operations, analysisData, cancellationToken); } finally { s_visitorPool.Free(visitor); } } private void Visit(ISymbol containingSymbol, IEnumerable<IOperation> operations, AnalysisData analysisData, CancellationToken cancellationToken) { Debug.Assert(_currentContainingSymbol == null); Debug.Assert(_currentAnalysisData == null); Debug.Assert(_currentRootOperation == null); Debug.Assert(_pendingWritesMap == null); _pendingWritesMap = PooledDictionary<IAssignmentOperation, PooledHashSet<(ISymbol, IOperation)>>.GetInstance(); try { _currentContainingSymbol = containingSymbol; _currentAnalysisData = analysisData; _cancellationToken = cancellationToken; foreach (var operation in operations) { cancellationToken.ThrowIfCancellationRequested(); _currentRootOperation = operation; Visit(operation); } } finally { _currentContainingSymbol = null; _currentAnalysisData = null; _currentRootOperation = null; _cancellationToken = default; foreach (var pendingWrites in _pendingWritesMap.Values) { pendingWrites.Free(); } _pendingWritesMap.Free(); _pendingWritesMap = null; } } private void OnReadReferenceFound(ISymbol symbol) => _currentAnalysisData.OnReadReferenceFound(symbol); private void OnWriteReferenceFound(ISymbol symbol, IOperation operation, ValueUsageInfo valueUsageInfo) { // maybeWritten == 'ref' argument. var isRef = valueUsageInfo == ValueUsageInfo.ReadableWritableReference; _currentAnalysisData.OnWriteReferenceFound(symbol, operation, maybeWritten: isRef, isRef); ProcessPossibleDelegateCreationAssignment(symbol, operation); } private void OnLValueCaptureFound(ISymbol symbol, IOperation operation, CaptureId captureId) => _currentAnalysisData.OnLValueCaptureFound(symbol, operation, captureId); private void OnLValueDereferenceFound(CaptureId captureId) => _currentAnalysisData.OnLValueDereferenceFound(captureId); private void OnReferenceFound(ISymbol symbol, IOperation operation) { Debug.Assert(symbol != null); var valueUsageInfo = operation.GetValueUsageInfo(_currentContainingSymbol); var isReadFrom = valueUsageInfo.IsReadFrom(); var isWrittenTo = valueUsageInfo.IsWrittenTo(); if (isWrittenTo && MakePendingWrite(operation, symbolOpt: symbol)) { // Certain writes are processed at a later visit // and are marked as a pending write for post processing. // For example, consider the write to 'x' in "x = M(x, ...)". // We visit the Target (left) of assignment before visiting the Value (right) // of the assignment, as there might be expressions on the left that are evaluated first. // We don't want to mark the symbol read while processing the left of assignment // as there can be references on the right, which reads the prior value. // Instead we mark this as a pending write, which will be processed when we finish visiting the assignment. isWrittenTo = false; } if (isReadFrom) { if (operation.Parent is IFlowCaptureOperation flowCapture && _currentAnalysisData.IsLValueFlowCapture(flowCapture.Id)) { OnLValueCaptureFound(symbol, operation, flowCapture.Id); // For compound assignments, the flow capture can be both an R-Value and an L-Value capture. if (_currentAnalysisData.IsRValueFlowCapture(flowCapture.Id)) { OnReadReferenceFound(symbol); } } else { OnReadReferenceFound(symbol); } } if (isWrittenTo) { OnWriteReferenceFound(symbol, operation, valueUsageInfo); } if (operation.Parent is IIncrementOrDecrementOperation && operation.Parent.Parent?.Kind != OperationKind.ExpressionStatement) { OnReadReferenceFound(symbol); } } private bool MakePendingWrite(IOperation operation, ISymbol symbolOpt) { Debug.Assert(symbolOpt != null || operation.Kind == OperationKind.FlowCaptureReference); if (operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation) { var set = PooledHashSet<(ISymbol, IOperation)>.GetInstance(); set.Add((symbolOpt, operation)); _pendingWritesMap.Add(assignmentOperation, set); return true; } else if (operation.IsInLeftOfDeconstructionAssignment(out var deconstructionAssignment)) { if (!_pendingWritesMap.TryGetValue(deconstructionAssignment, out var set)) { set = PooledHashSet<(ISymbol, IOperation)>.GetInstance(); _pendingWritesMap.Add(deconstructionAssignment, set); } set.Add((symbolOpt, operation)); return true; } return false; } private void ProcessPendingWritesForAssignmentTarget(IAssignmentOperation operation) { if (_pendingWritesMap.TryGetValue(operation, out var pendingWrites)) { var isUsedCompountAssignment = operation.IsAnyCompoundAssignment() && operation.Parent?.Kind != OperationKind.ExpressionStatement; foreach (var (symbolOpt, write) in pendingWrites) { if (write.Kind != OperationKind.FlowCaptureReference) { Debug.Assert(symbolOpt != null); OnWriteReferenceFound(symbolOpt, write, ValueUsageInfo.Write); if (isUsedCompountAssignment) { OnReadReferenceFound(symbolOpt); } } else { Debug.Assert(symbolOpt == null); var captureReference = (IFlowCaptureReferenceOperation)write; Debug.Assert(_currentAnalysisData.IsLValueFlowCapture(captureReference.Id)); OnLValueDereferenceFound(captureReference.Id); } } _pendingWritesMap.Remove(operation); } } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { base.VisitSimpleAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { base.VisitCompoundAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { base.VisitCoalesceAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { base.VisitDeconstructionAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitLocalReference(ILocalReferenceOperation operation) { if (operation.Local.IsRef) { // Bail out for ref locals. // We need points to analysis for analyzing writes to ref locals, which is currently not supported. return; } OnReferenceFound(operation.Local, operation); } public override void VisitParameterReference(IParameterReferenceOperation operation) => OnReferenceFound(operation.Parameter, operation); public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { var variableInitializer = operation.GetVariableInitializer(); if (variableInitializer != null || operation.Parent is IForEachLoopOperation forEachLoop && forEachLoop.LoopControlVariable == operation || operation.Parent is ICatchClauseOperation catchClause && catchClause.ExceptionDeclarationOrExpression == operation) { OnWriteReferenceFound(operation.Symbol, operation, ValueUsageInfo.Write); } base.VisitVariableDeclarator(operation); } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { base.VisitFlowCaptureReference(operation); if (_currentAnalysisData.IsLValueFlowCapture(operation.Id) && !MakePendingWrite(operation, symbolOpt: null)) { OnLValueDereferenceFound(operation.Id); } } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { if (operation.DeclaredSymbol != null) { OnReferenceFound(operation.DeclaredSymbol, operation); } } public override void VisitInvocation(IInvocationOperation operation) { base.VisitInvocation(operation); switch (operation.TargetMethod.MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.DelegateInvoke: if (operation.Instance != null) { AnalyzePossibleDelegateInvocation(operation.Instance); } else { _currentAnalysisData.ResetState(); } break; case MethodKind.LocalFunction: AnalyzeLocalFunctionInvocation(operation.TargetMethod); break; } } private void AnalyzeLocalFunctionInvocation(IMethodSymbol localFunction) { Debug.Assert(localFunction.IsLocalFunction()); var newAnalysisData = _currentAnalysisData.AnalyzeLocalFunctionInvocation(localFunction, _cancellationToken); _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(newAnalysisData); } private void AnalyzeLambdaInvocation(IFlowAnonymousFunctionOperation lambda) { var newAnalysisData = _currentAnalysisData.AnalyzeLambdaInvocation(lambda, _cancellationToken); _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(newAnalysisData); } public override void VisitArgument(IArgumentOperation operation) { base.VisitArgument(operation); if (_currentAnalysisData.IsTrackingDelegateCreationTargets && operation.Value.Type.IsDelegateType()) { // Delegate argument might be captured and invoked multiple times. // So, conservatively reset the state. _currentAnalysisData.ResetState(); } } public override void VisitLocalFunction(ILocalFunctionOperation operation) { // Skip visiting if we are doing an operation tree walk. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitLocalFunction(operation); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { // Skip visiting if we are doing an operation tree walk. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitAnonymousFunction(operation); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { // Skip visiting if we are not analyzing an invocation of this lambda. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitFlowAnonymousFunction(operation); } private void ProcessPossibleDelegateCreationAssignment(ISymbol symbol, IOperation write) { if (!_currentAnalysisData.IsTrackingDelegateCreationTargets || symbol.GetSymbolType()?.TypeKind != TypeKind.Delegate) { return; } IOperation initializerValue = null; if (write is IVariableDeclaratorOperation variableDeclarator) { initializerValue = variableDeclarator.GetVariableInitializer()?.Value; } else if (write.Parent is ISimpleAssignmentOperation simpleAssignment) { initializerValue = simpleAssignment.Value; } if (initializerValue != null) { ProcessPossibleDelegateCreation(initializerValue, write); } } private void ProcessPossibleDelegateCreation(IOperation creation, IOperation write) { var currentOperation = creation; while (true) { switch (currentOperation.Kind) { case OperationKind.Conversion: currentOperation = ((IConversionOperation)currentOperation).Operand; continue; case OperationKind.Parenthesized: currentOperation = ((IParenthesizedOperation)currentOperation).Operand; continue; case OperationKind.DelegateCreation: currentOperation = ((IDelegateCreationOperation)currentOperation).Target; continue; case OperationKind.AnonymousFunction: // We don't support lambda target analysis for operation tree // and control flow graph should have replaced 'AnonymousFunction' nodes // with 'FlowAnonymousFunction' nodes. throw ExceptionUtilities.Unreachable; case OperationKind.FlowAnonymousFunction: _currentAnalysisData.SetLambdaTargetForDelegate(write, (IFlowAnonymousFunctionOperation)currentOperation); return; case OperationKind.MethodReference: var methodReference = (IMethodReferenceOperation)currentOperation; if (methodReference.Method.IsLocalFunction()) { _currentAnalysisData.SetLocalFunctionTargetForDelegate(write, methodReference); } else { _currentAnalysisData.SetEmptyInvocationTargetsForDelegate(write); } return; case OperationKind.LocalReference: var localReference = (ILocalReferenceOperation)currentOperation; _currentAnalysisData.SetTargetsFromSymbolForDelegate(write, localReference.Local); return; case OperationKind.ParameterReference: var parameterReference = (IParameterReferenceOperation)currentOperation; _currentAnalysisData.SetTargetsFromSymbolForDelegate(write, parameterReference.Parameter); return; case OperationKind.Literal: if (currentOperation.ConstantValue.Value is null) { _currentAnalysisData.SetEmptyInvocationTargetsForDelegate(write); } return; default: return; } } } private void AnalyzePossibleDelegateInvocation(IOperation operation) { Debug.Assert(operation.Type.IsDelegateType()); if (!_currentAnalysisData.IsTrackingDelegateCreationTargets) { return; } ProcessPossibleDelegateCreation(creation: operation, write: operation); if (!_currentAnalysisData.TryGetDelegateInvocationTargets(operation, out var targets)) { // Failed to identify targets, so conservatively reset the state. _currentAnalysisData.ResetState(); return; } switch (targets.Count) { case 0: // None of the delegate invocation targets are lambda/local functions. break; case 1: // Single target. // If we know it is an explicit invocation that will certainly be invoked, // analyze it explicitly and overwrite current state. AnalyzeDelegateInvocation(targets.Single()); break; default: // Multiple potential lambda/local function targets. // Analyze each one, merging the outputs from all. var savedCurrentAnalysisData = _currentAnalysisData.CreateBlockAnalysisData(); savedCurrentAnalysisData.SetAnalysisDataFrom(_currentAnalysisData.CurrentBlockAnalysisData); var mergedAnalysisData = _currentAnalysisData.CreateBlockAnalysisData(); foreach (var target in targets) { _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(savedCurrentAnalysisData); AnalyzeDelegateInvocation(target); mergedAnalysisData = BasicBlockAnalysisData.Merge(mergedAnalysisData, _currentAnalysisData.CurrentBlockAnalysisData, _currentAnalysisData.TrackAllocatedBlockAnalysisData); } _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(mergedAnalysisData); break; } return; // Local functions. void AnalyzeDelegateInvocation(IOperation target) { switch (target.Kind) { case OperationKind.FlowAnonymousFunction: AnalyzeLambdaInvocation((IFlowAnonymousFunctionOperation)target); break; case OperationKind.MethodReference: AnalyzeLocalFunctionInvocation(((IMethodReferenceOperation)target).Method); break; default: throw ExceptionUtilities.Unreachable; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Operations walker used for walking high-level operation tree /// as well as control flow graph based operations. /// </summary> private sealed class Walker : OperationWalker { private AnalysisData _currentAnalysisData; private ISymbol _currentContainingSymbol; private IOperation _currentRootOperation; private CancellationToken _cancellationToken; private PooledDictionary<IAssignmentOperation, PooledHashSet<(ISymbol, IOperation)>> _pendingWritesMap; private static readonly ObjectPool<Walker> s_visitorPool = new(() => new Walker()); private Walker() { } public static void AnalyzeOperationsAndUpdateData( ISymbol containingSymbol, IEnumerable<IOperation> operations, AnalysisData analysisData, CancellationToken cancellationToken) { var visitor = s_visitorPool.Allocate(); try { visitor.Visit(containingSymbol, operations, analysisData, cancellationToken); } finally { s_visitorPool.Free(visitor); } } private void Visit(ISymbol containingSymbol, IEnumerable<IOperation> operations, AnalysisData analysisData, CancellationToken cancellationToken) { Debug.Assert(_currentContainingSymbol == null); Debug.Assert(_currentAnalysisData == null); Debug.Assert(_currentRootOperation == null); Debug.Assert(_pendingWritesMap == null); _pendingWritesMap = PooledDictionary<IAssignmentOperation, PooledHashSet<(ISymbol, IOperation)>>.GetInstance(); try { _currentContainingSymbol = containingSymbol; _currentAnalysisData = analysisData; _cancellationToken = cancellationToken; foreach (var operation in operations) { cancellationToken.ThrowIfCancellationRequested(); _currentRootOperation = operation; Visit(operation); } } finally { _currentContainingSymbol = null; _currentAnalysisData = null; _currentRootOperation = null; _cancellationToken = default; foreach (var pendingWrites in _pendingWritesMap.Values) { pendingWrites.Free(); } _pendingWritesMap.Free(); _pendingWritesMap = null; } } private void OnReadReferenceFound(ISymbol symbol) => _currentAnalysisData.OnReadReferenceFound(symbol); private void OnWriteReferenceFound(ISymbol symbol, IOperation operation, ValueUsageInfo valueUsageInfo) { // maybeWritten == 'ref' argument. var isRef = valueUsageInfo == ValueUsageInfo.ReadableWritableReference; _currentAnalysisData.OnWriteReferenceFound(symbol, operation, maybeWritten: isRef, isRef); ProcessPossibleDelegateCreationAssignment(symbol, operation); } private void OnLValueCaptureFound(ISymbol symbol, IOperation operation, CaptureId captureId) => _currentAnalysisData.OnLValueCaptureFound(symbol, operation, captureId); private void OnLValueDereferenceFound(CaptureId captureId) => _currentAnalysisData.OnLValueDereferenceFound(captureId); private void OnReferenceFound(ISymbol symbol, IOperation operation) { Debug.Assert(symbol != null); var valueUsageInfo = operation.GetValueUsageInfo(_currentContainingSymbol); var isReadFrom = valueUsageInfo.IsReadFrom(); var isWrittenTo = valueUsageInfo.IsWrittenTo(); if (isWrittenTo && MakePendingWrite(operation, symbolOpt: symbol)) { // Certain writes are processed at a later visit // and are marked as a pending write for post processing. // For example, consider the write to 'x' in "x = M(x, ...)". // We visit the Target (left) of assignment before visiting the Value (right) // of the assignment, as there might be expressions on the left that are evaluated first. // We don't want to mark the symbol read while processing the left of assignment // as there can be references on the right, which reads the prior value. // Instead we mark this as a pending write, which will be processed when we finish visiting the assignment. isWrittenTo = false; } if (isReadFrom) { if (operation.Parent is IFlowCaptureOperation flowCapture && _currentAnalysisData.IsLValueFlowCapture(flowCapture.Id)) { OnLValueCaptureFound(symbol, operation, flowCapture.Id); // For compound assignments, the flow capture can be both an R-Value and an L-Value capture. if (_currentAnalysisData.IsRValueFlowCapture(flowCapture.Id)) { OnReadReferenceFound(symbol); } } else { OnReadReferenceFound(symbol); } } if (isWrittenTo) { OnWriteReferenceFound(symbol, operation, valueUsageInfo); } if (operation.Parent is IIncrementOrDecrementOperation && operation.Parent.Parent?.Kind != OperationKind.ExpressionStatement) { OnReadReferenceFound(symbol); } } private bool MakePendingWrite(IOperation operation, ISymbol symbolOpt) { Debug.Assert(symbolOpt != null || operation.Kind == OperationKind.FlowCaptureReference); if (operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation) { var set = PooledHashSet<(ISymbol, IOperation)>.GetInstance(); set.Add((symbolOpt, operation)); _pendingWritesMap.Add(assignmentOperation, set); return true; } else if (operation.IsInLeftOfDeconstructionAssignment(out var deconstructionAssignment)) { if (!_pendingWritesMap.TryGetValue(deconstructionAssignment, out var set)) { set = PooledHashSet<(ISymbol, IOperation)>.GetInstance(); _pendingWritesMap.Add(deconstructionAssignment, set); } set.Add((symbolOpt, operation)); return true; } return false; } private void ProcessPendingWritesForAssignmentTarget(IAssignmentOperation operation) { if (_pendingWritesMap.TryGetValue(operation, out var pendingWrites)) { var isUsedCompountAssignment = operation.IsAnyCompoundAssignment() && operation.Parent?.Kind != OperationKind.ExpressionStatement; foreach (var (symbolOpt, write) in pendingWrites) { if (write.Kind != OperationKind.FlowCaptureReference) { Debug.Assert(symbolOpt != null); OnWriteReferenceFound(symbolOpt, write, ValueUsageInfo.Write); if (isUsedCompountAssignment) { OnReadReferenceFound(symbolOpt); } } else { Debug.Assert(symbolOpt == null); var captureReference = (IFlowCaptureReferenceOperation)write; Debug.Assert(_currentAnalysisData.IsLValueFlowCapture(captureReference.Id)); OnLValueDereferenceFound(captureReference.Id); } } _pendingWritesMap.Remove(operation); } } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { base.VisitSimpleAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { base.VisitCompoundAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { base.VisitCoalesceAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { base.VisitDeconstructionAssignment(operation); ProcessPendingWritesForAssignmentTarget(operation); } public override void VisitLocalReference(ILocalReferenceOperation operation) { if (operation.Local.IsRef) { // Bail out for ref locals. // We need points to analysis for analyzing writes to ref locals, which is currently not supported. return; } OnReferenceFound(operation.Local, operation); } public override void VisitParameterReference(IParameterReferenceOperation operation) => OnReferenceFound(operation.Parameter, operation); public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { var variableInitializer = operation.GetVariableInitializer(); if (variableInitializer != null || operation.Parent is IForEachLoopOperation forEachLoop && forEachLoop.LoopControlVariable == operation || operation.Parent is ICatchClauseOperation catchClause && catchClause.ExceptionDeclarationOrExpression == operation) { OnWriteReferenceFound(operation.Symbol, operation, ValueUsageInfo.Write); } base.VisitVariableDeclarator(operation); } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { base.VisitFlowCaptureReference(operation); if (_currentAnalysisData.IsLValueFlowCapture(operation.Id) && !MakePendingWrite(operation, symbolOpt: null)) { OnLValueDereferenceFound(operation.Id); } } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { if (operation.DeclaredSymbol != null) { OnReferenceFound(operation.DeclaredSymbol, operation); } } public override void VisitInvocation(IInvocationOperation operation) { base.VisitInvocation(operation); switch (operation.TargetMethod.MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.DelegateInvoke: if (operation.Instance != null) { AnalyzePossibleDelegateInvocation(operation.Instance); } else { _currentAnalysisData.ResetState(); } break; case MethodKind.LocalFunction: AnalyzeLocalFunctionInvocation(operation.TargetMethod); break; } } private void AnalyzeLocalFunctionInvocation(IMethodSymbol localFunction) { Debug.Assert(localFunction.IsLocalFunction()); var newAnalysisData = _currentAnalysisData.AnalyzeLocalFunctionInvocation(localFunction, _cancellationToken); _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(newAnalysisData); } private void AnalyzeLambdaInvocation(IFlowAnonymousFunctionOperation lambda) { var newAnalysisData = _currentAnalysisData.AnalyzeLambdaInvocation(lambda, _cancellationToken); _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(newAnalysisData); } public override void VisitArgument(IArgumentOperation operation) { base.VisitArgument(operation); if (_currentAnalysisData.IsTrackingDelegateCreationTargets && operation.Value.Type.IsDelegateType()) { // Delegate argument might be captured and invoked multiple times. // So, conservatively reset the state. _currentAnalysisData.ResetState(); } } public override void VisitLocalFunction(ILocalFunctionOperation operation) { // Skip visiting if we are doing an operation tree walk. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitLocalFunction(operation); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { // Skip visiting if we are doing an operation tree walk. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitAnonymousFunction(operation); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { // Skip visiting if we are not analyzing an invocation of this lambda. // This will only happen if the operation is not the current root operation. if (_currentRootOperation != operation) { return; } base.VisitFlowAnonymousFunction(operation); } private void ProcessPossibleDelegateCreationAssignment(ISymbol symbol, IOperation write) { if (!_currentAnalysisData.IsTrackingDelegateCreationTargets || symbol.GetSymbolType()?.TypeKind != TypeKind.Delegate) { return; } IOperation initializerValue = null; if (write is IVariableDeclaratorOperation variableDeclarator) { initializerValue = variableDeclarator.GetVariableInitializer()?.Value; } else if (write.Parent is ISimpleAssignmentOperation simpleAssignment) { initializerValue = simpleAssignment.Value; } if (initializerValue != null) { ProcessPossibleDelegateCreation(initializerValue, write); } } private void ProcessPossibleDelegateCreation(IOperation creation, IOperation write) { var currentOperation = creation; while (true) { switch (currentOperation.Kind) { case OperationKind.Conversion: currentOperation = ((IConversionOperation)currentOperation).Operand; continue; case OperationKind.Parenthesized: currentOperation = ((IParenthesizedOperation)currentOperation).Operand; continue; case OperationKind.DelegateCreation: currentOperation = ((IDelegateCreationOperation)currentOperation).Target; continue; case OperationKind.AnonymousFunction: // We don't support lambda target analysis for operation tree // and control flow graph should have replaced 'AnonymousFunction' nodes // with 'FlowAnonymousFunction' nodes. throw ExceptionUtilities.Unreachable; case OperationKind.FlowAnonymousFunction: _currentAnalysisData.SetLambdaTargetForDelegate(write, (IFlowAnonymousFunctionOperation)currentOperation); return; case OperationKind.MethodReference: var methodReference = (IMethodReferenceOperation)currentOperation; if (methodReference.Method.IsLocalFunction()) { _currentAnalysisData.SetLocalFunctionTargetForDelegate(write, methodReference); } else { _currentAnalysisData.SetEmptyInvocationTargetsForDelegate(write); } return; case OperationKind.LocalReference: var localReference = (ILocalReferenceOperation)currentOperation; _currentAnalysisData.SetTargetsFromSymbolForDelegate(write, localReference.Local); return; case OperationKind.ParameterReference: var parameterReference = (IParameterReferenceOperation)currentOperation; _currentAnalysisData.SetTargetsFromSymbolForDelegate(write, parameterReference.Parameter); return; case OperationKind.Literal: if (currentOperation.ConstantValue.Value is null) { _currentAnalysisData.SetEmptyInvocationTargetsForDelegate(write); } return; default: return; } } } private void AnalyzePossibleDelegateInvocation(IOperation operation) { Debug.Assert(operation.Type.IsDelegateType()); if (!_currentAnalysisData.IsTrackingDelegateCreationTargets) { return; } ProcessPossibleDelegateCreation(creation: operation, write: operation); if (!_currentAnalysisData.TryGetDelegateInvocationTargets(operation, out var targets)) { // Failed to identify targets, so conservatively reset the state. _currentAnalysisData.ResetState(); return; } switch (targets.Count) { case 0: // None of the delegate invocation targets are lambda/local functions. break; case 1: // Single target. // If we know it is an explicit invocation that will certainly be invoked, // analyze it explicitly and overwrite current state. AnalyzeDelegateInvocation(targets.Single()); break; default: // Multiple potential lambda/local function targets. // Analyze each one, merging the outputs from all. var savedCurrentAnalysisData = _currentAnalysisData.CreateBlockAnalysisData(); savedCurrentAnalysisData.SetAnalysisDataFrom(_currentAnalysisData.CurrentBlockAnalysisData); var mergedAnalysisData = _currentAnalysisData.CreateBlockAnalysisData(); foreach (var target in targets) { _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(savedCurrentAnalysisData); AnalyzeDelegateInvocation(target); mergedAnalysisData = BasicBlockAnalysisData.Merge(mergedAnalysisData, _currentAnalysisData.CurrentBlockAnalysisData, _currentAnalysisData.TrackAllocatedBlockAnalysisData); } _currentAnalysisData.SetCurrentBlockAnalysisDataFrom(mergedAnalysisData); break; } return; // Local functions. void AnalyzeDelegateInvocation(IOperation target) { switch (target.Kind) { case OperationKind.FlowAnonymousFunction: AnalyzeLambdaInvocation((IFlowAnonymousFunctionOperation)target); break; case OperationKind.MethodReference: AnalyzeLocalFunctionInvocation(((IMethodReferenceOperation)target).Method); break; default: throw ExceptionUtilities.Unreachable; } } } } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingProjectExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingProjectExtensions { public static string? GetDebugName(this ProjectId projectId) => projectId.DebugName; public static Task<bool> HasSuccessfullyLoadedAsync(this Project project, CancellationToken cancellationToken) => project.HasSuccessfullyLoadedAsync(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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingProjectExtensions { public static string? GetDebugName(this ProjectId projectId) => projectId.DebugName; public static Task<bool> HasSuccessfullyLoadedAsync(this Project project, CancellationToken cancellationToken) => project.HasSuccessfullyLoadedAsync(cancellationToken); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableDictionaryBuilderTestBase.cs
// Licensed to the .NET Foundation under one or more 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/System.Collections.Immutable/tests/ImmutableDictionaryBuilderTestBase.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.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase { [Fact] public void Add() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add(new KeyValuePair<string, int>("six", 6)); Assert.Equal(5, builder["five"]); Assert.Equal(6, builder["six"]); Assert.False(builder.ContainsKey("four")); } /// <summary> /// Verifies that "adding" an entry to the dictionary that already exists /// with exactly the same key and value will *not* throw an exception. /// </summary> /// <remarks> /// The BCL Dictionary type would throw in this circumstance. /// But in an immutable world, not only do we not care so much since the result is the same. /// </remarks> [Fact] public void AddExactDuplicate() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add("five", 5); Assert.Equal(1, builder.Count); } [Fact] public void AddExistingKeyWithDifferentValue() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); Assert.Throws<ArgumentException>(null, () => builder.Add("five", 6)); } [Fact] public void Indexer() { var builder = this.GetBuilder<string, int>(); // Set and set again. builder["five"] = 5; Assert.Equal(5, builder["five"]); builder["five"] = 5; Assert.Equal(5, builder["five"]); // Set to a new value. builder["five"] = 50; Assert.Equal(50, builder["five"]); // Retrieve an invalid value. Assert.Throws<KeyNotFoundException>(() => builder["foo"]); } [Fact] public void ContainsPair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5))); } [Fact] public void RemovePair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5))); Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1))); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void RemoveKey() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); builder.Remove("five"); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void CopyTo() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); var array = new KeyValuePair<string, int>[2]; // intentionally larger than source. builder.CopyTo(array, 1); Assert.Equal(new KeyValuePair<string, int>(), array[0]); Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]); Assert.Throws<ArgumentNullException>("array", () => builder.CopyTo(null!, 0)); } [Fact] public void IsReadOnly() { var builder = this.GetBuilder<string, int>(); Assert.False(builder.IsReadOnly); } [Fact] public void Keys() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys); CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray()); } [Fact] public void Values() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values); CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray()); } [Fact] public void TryGetValue() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.TryGetValue("five", out int value) && value == 5); Assert.True(builder.TryGetValue("six", out value) && value == 6); Assert.False(builder.TryGetValue("four", out value)); Assert.Equal(0, value); } [Fact] public void EnumerateTest() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); using (var enumerator = builder.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } var manualEnum = builder.GetEnumerator(); Assert.Equal(default(KeyValuePair<string, int>), manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Equal(default(KeyValuePair<string, int>), manualEnum.Current); } [Fact] public void IDictionaryMembers() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); Assert.True(dictionary.Contains("a")); Assert.Equal(1, dictionary["a"]); Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray()); dictionary["a"] = 2; Assert.Equal(2, dictionary["a"]); dictionary.Remove("a"); Assert.False(dictionary.Contains("a")); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); } [Fact] public void IDictionaryEnumerator() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void ICollectionMembers() { var builder = this.GetBuilder<string, int>(); var collection = (ICollection)builder; collection.CopyTo(Array.Empty<object>(), 0); builder.Add("b", 2); Assert.True(builder.ContainsKey("b")); var array = new object[builder.Count + 1]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new object?[] { null, new KeyValuePair<string, int>("b", 2) }, array); var entryArray = new DictionaryEntry[builder.Count + 1]; collection.CopyTo(entryArray, 1); Assert.Equal(default(DictionaryEntry), entryArray[0]); Assert.Equal(new DictionaryEntry[] { default, new DictionaryEntry("b", 2) }, entryArray); Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey) where TKey : notnull; /// <summary> /// Gets the Builder for a given dictionary instance. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The builder.</returns> protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue>? basis = null) where TKey : notnull; /// <summary> /// Gets an empty immutable dictionary. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The immutable dictionary.</returns> protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>() where TKey : notnull; protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); } }
// Licensed to the .NET Foundation under one or more 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/System.Collections.Immutable/tests/ImmutableDictionaryBuilderTestBase.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.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase { [Fact] public void Add() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add(new KeyValuePair<string, int>("six", 6)); Assert.Equal(5, builder["five"]); Assert.Equal(6, builder["six"]); Assert.False(builder.ContainsKey("four")); } /// <summary> /// Verifies that "adding" an entry to the dictionary that already exists /// with exactly the same key and value will *not* throw an exception. /// </summary> /// <remarks> /// The BCL Dictionary type would throw in this circumstance. /// But in an immutable world, not only do we not care so much since the result is the same. /// </remarks> [Fact] public void AddExactDuplicate() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add("five", 5); Assert.Equal(1, builder.Count); } [Fact] public void AddExistingKeyWithDifferentValue() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); Assert.Throws<ArgumentException>(null, () => builder.Add("five", 6)); } [Fact] public void Indexer() { var builder = this.GetBuilder<string, int>(); // Set and set again. builder["five"] = 5; Assert.Equal(5, builder["five"]); builder["five"] = 5; Assert.Equal(5, builder["five"]); // Set to a new value. builder["five"] = 50; Assert.Equal(50, builder["five"]); // Retrieve an invalid value. Assert.Throws<KeyNotFoundException>(() => builder["foo"]); } [Fact] public void ContainsPair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5))); } [Fact] public void RemovePair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5))); Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1))); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void RemoveKey() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); builder.Remove("five"); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void CopyTo() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); var array = new KeyValuePair<string, int>[2]; // intentionally larger than source. builder.CopyTo(array, 1); Assert.Equal(new KeyValuePair<string, int>(), array[0]); Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]); Assert.Throws<ArgumentNullException>("array", () => builder.CopyTo(null!, 0)); } [Fact] public void IsReadOnly() { var builder = this.GetBuilder<string, int>(); Assert.False(builder.IsReadOnly); } [Fact] public void Keys() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys); CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray()); } [Fact] public void Values() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values); CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray()); } [Fact] public void TryGetValue() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.TryGetValue("five", out int value) && value == 5); Assert.True(builder.TryGetValue("six", out value) && value == 6); Assert.False(builder.TryGetValue("four", out value)); Assert.Equal(0, value); } [Fact] public void EnumerateTest() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); using (var enumerator = builder.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } var manualEnum = builder.GetEnumerator(); Assert.Equal(default(KeyValuePair<string, int>), manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Equal(default(KeyValuePair<string, int>), manualEnum.Current); } [Fact] public void IDictionaryMembers() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); Assert.True(dictionary.Contains("a")); Assert.Equal(1, dictionary["a"]); Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray()); dictionary["a"] = 2; Assert.Equal(2, dictionary["a"]); dictionary.Remove("a"); Assert.False(dictionary.Contains("a")); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); } [Fact] public void IDictionaryEnumerator() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void ICollectionMembers() { var builder = this.GetBuilder<string, int>(); var collection = (ICollection)builder; collection.CopyTo(Array.Empty<object>(), 0); builder.Add("b", 2); Assert.True(builder.ContainsKey("b")); var array = new object[builder.Count + 1]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new object?[] { null, new KeyValuePair<string, int>("b", 2) }, array); var entryArray = new DictionaryEntry[builder.Count + 1]; collection.CopyTo(entryArray, 1); Assert.Equal(default(DictionaryEntry), entryArray[0]); Assert.Equal(new DictionaryEntry[] { default, new DictionaryEntry("b", 2) }, entryArray); Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey) where TKey : notnull; /// <summary> /// Gets the Builder for a given dictionary instance. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The builder.</returns> protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue>? basis = null) where TKey : notnull; /// <summary> /// Gets an empty immutable dictionary. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The immutable dictionary.</returns> protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>() where TKey : notnull; protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices { internal partial class CSharpSymbolDisplayService : AbstractSymbolDisplayService { public CSharpSymbolDisplayService(HostLanguageServices provider) : base(provider.GetService<IAnonymousTypeDisplayService>()) { } protected override AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => new SymbolDescriptionBuilder(semanticModel, position, workspace, AnonymousTypeDisplayService, 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; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices { internal partial class CSharpSymbolDisplayService : AbstractSymbolDisplayService { public CSharpSymbolDisplayService(HostLanguageServices provider) : base(provider.GetService<IAnonymousTypeDisplayService>()) { } protected override AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => new SymbolDescriptionBuilder(semanticModel, position, workspace, AnonymousTypeDisplayService, cancellationToken); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseNullPropagation; namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseNullPropagationDiagnosticAnalyzer : AbstractUseNullPropagationDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax, BinaryExpressionSyntax, InvocationExpressionSyntax, MemberAccessExpressionSyntax, ConditionalAccessExpressionSyntax, ElementAccessExpressionSyntax> { protected override bool ShouldAnalyze(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); protected override bool TryAnalyzePatternCondition( ISyntaxFacts syntaxFacts, SyntaxNode conditionNode, [NotNullWhen(true)] out SyntaxNode? conditionPartToCheck, out bool isEquals) { conditionPartToCheck = null; isEquals = true; if (!(conditionNode is IsPatternExpressionSyntax patternExpression)) { return false; } if (!(patternExpression.Pattern is ConstantPatternSyntax constantPattern)) { return false; } if (!syntaxFacts.IsNullLiteralExpression(constantPattern.Expression)) { return false; } conditionPartToCheck = patternExpression.Expression; 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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseNullPropagation; namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseNullPropagationDiagnosticAnalyzer : AbstractUseNullPropagationDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax, BinaryExpressionSyntax, InvocationExpressionSyntax, MemberAccessExpressionSyntax, ConditionalAccessExpressionSyntax, ElementAccessExpressionSyntax> { protected override bool ShouldAnalyze(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); protected override bool TryAnalyzePatternCondition( ISyntaxFacts syntaxFacts, SyntaxNode conditionNode, [NotNullWhen(true)] out SyntaxNode? conditionPartToCheck, out bool isEquals) { conditionPartToCheck = null; isEquals = true; if (!(conditionNode is IsPatternExpressionSyntax patternExpression)) { return false; } if (!(patternExpression.Pattern is ConstantPatternSyntax constantPattern)) { return false; } if (!syntaxFacts.IsNullLiteralExpression(constantPattern.Expression)) { return false; } conditionPartToCheck = patternExpression.Expression; return true; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/MemberDescriptor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.IO; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.RuntimeMembers { [Flags()] internal enum MemberFlags : byte { // BEGIN Mutually exclusive Member kinds: Method = 0x01, Field = 0x02, Constructor = 0x04, PropertyGet = 0x08, Property = 0x10, // END Mutually exclusive Member kinds KindMask = 0x1F, Static = 0x20, Virtual = 0x40, // Virtual in CLR terms, i.e. sealed should be accepted. } /// <summary> /// Structure that describes a member of a type. /// </summary> internal readonly struct MemberDescriptor { public readonly MemberFlags Flags; /// <summary> /// Id/token of containing type, usually value from some enum. /// For example from SpecialType enum. /// I am not using SpecialType as the type for this field because /// VB runtime types are not part of SpecialType. /// /// So, the implication is that any type ids we use outside of the SpecialType /// (either for the VB runtime classes, or types like System.Task etc.) will need /// to use IDs that are all mutually disjoint. /// </summary> public readonly short DeclaringTypeId; public string? DeclaringTypeMetadataName { get { return DeclaringTypeId <= (int)SpecialType.Count ? ((SpecialType)DeclaringTypeId).GetMetadataName() : ((WellKnownType)DeclaringTypeId).GetMetadataName(); } } public readonly ushort Arity; public readonly string Name; /// <summary> /// Signature of the field or method, similar to metadata signature, /// but with the following exceptions: /// 1) Truncated on the left, for methods starts at [ParamCount], for fields at [Type] /// 2) Type tokens are not compressed /// 3) BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | I | U | Void types are encoded by /// using VALUETYPE+typeId notation. /// 4) array bounds are not included. /// 5) modifiers are not included. /// 6) (CLASS | VALUETYPE) are omitted after GENERICINST /// </summary> public readonly ImmutableArray<byte> Signature; /// <summary> /// Applicable only to properties and methods, throws otherwise. /// </summary> public int ParametersCount { get { MemberFlags memberKind = Flags & MemberFlags.KindMask; switch (memberKind) { case MemberFlags.Constructor: case MemberFlags.Method: case MemberFlags.PropertyGet: case MemberFlags.Property: return Signature[0]; default: throw ExceptionUtilities.UnexpectedValue(memberKind); } } } public MemberDescriptor( MemberFlags Flags, short DeclaringTypeId, string Name, ImmutableArray<byte> Signature, ushort Arity = 0) { this.Flags = Flags; this.DeclaringTypeId = DeclaringTypeId; this.Name = Name; this.Arity = Arity; this.Signature = Signature; } internal static ImmutableArray<MemberDescriptor> InitializeFromStream(Stream stream, string[] nameTable) { int count = nameTable.Length; var builder = ImmutableArray.CreateBuilder<MemberDescriptor>(count); var signatureBuilder = ImmutableArray.CreateBuilder<byte>(); for (int i = 0; i < count; i++) { MemberFlags flags = (MemberFlags)stream.ReadByte(); short declaringTypeId = ReadTypeId(stream); ushort arity = (ushort)stream.ReadByte(); if ((flags & MemberFlags.Field) != 0) { ParseType(signatureBuilder, stream); } else { // Property, PropertyGet, Method or Constructor ParseMethodOrPropertySignature(signatureBuilder, stream); } builder.Add(new MemberDescriptor(flags, declaringTypeId, nameTable[i], signatureBuilder.ToImmutable(), arity)); signatureBuilder.Clear(); } return builder.ToImmutable(); } /// <summary> /// The type Id may be: /// (1) encoded in a single byte (for types below 255) /// (2) encoded in two bytes (255 + extension byte) for types below 512 /// </summary> private static short ReadTypeId(Stream stream) { var firstByte = (byte)stream.ReadByte(); if (firstByte == (byte)WellKnownType.ExtSentinel) { return (short)(stream.ReadByte() + WellKnownType.ExtSentinel); } else { return firstByte; } } private static void ParseMethodOrPropertySignature(ImmutableArray<byte>.Builder builder, Stream stream) { int paramCount = stream.ReadByte(); builder.Add((byte)paramCount); // Return type ParseType(builder, stream, allowByRef: true); // Parameters for (int i = 0; i < paramCount; i++) { ParseType(builder, stream, allowByRef: true); } } private static void ParseType(ImmutableArray<byte>.Builder builder, Stream stream, bool allowByRef = false) { while (true) { var typeCode = (SignatureTypeCode)stream.ReadByte(); builder.Add((byte)typeCode); switch (typeCode) { default: throw ExceptionUtilities.UnexpectedValue(typeCode); case SignatureTypeCode.TypeHandle: ParseTypeHandle(builder, stream); return; case SignatureTypeCode.GenericTypeParameter: case SignatureTypeCode.GenericMethodParameter: builder.Add((byte)stream.ReadByte()); return; case SignatureTypeCode.ByReference: if (!allowByRef) goto default; break; case SignatureTypeCode.SZArray: break; case SignatureTypeCode.Pointer: break; case SignatureTypeCode.GenericTypeInstance: ParseGenericTypeInstance(builder, stream); return; } allowByRef = false; } } /// <summary> /// Read a type Id from the stream and copy it into the builder. /// This may copy one or two bytes depending on the first one. /// </summary> private static void ParseTypeHandle(ImmutableArray<byte>.Builder builder, Stream stream) { var firstByte = (byte)stream.ReadByte(); builder.Add(firstByte); if (firstByte == (byte)WellKnownType.ExtSentinel) { var secondByte = (byte)stream.ReadByte(); builder.Add(secondByte); } } private static void ParseGenericTypeInstance(ImmutableArray<byte>.Builder builder, Stream stream) { ParseType(builder, stream); // Generic type parameters int argumentCount = stream.ReadByte(); builder.Add((byte)argumentCount); for (int i = 0; i < argumentCount; i++) { ParseType(builder, stream); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.IO; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.RuntimeMembers { [Flags()] internal enum MemberFlags : byte { // BEGIN Mutually exclusive Member kinds: Method = 0x01, Field = 0x02, Constructor = 0x04, PropertyGet = 0x08, Property = 0x10, // END Mutually exclusive Member kinds KindMask = 0x1F, Static = 0x20, Virtual = 0x40, // Virtual in CLR terms, i.e. sealed should be accepted. } /// <summary> /// Structure that describes a member of a type. /// </summary> internal readonly struct MemberDescriptor { public readonly MemberFlags Flags; /// <summary> /// Id/token of containing type, usually value from some enum. /// For example from SpecialType enum. /// I am not using SpecialType as the type for this field because /// VB runtime types are not part of SpecialType. /// /// So, the implication is that any type ids we use outside of the SpecialType /// (either for the VB runtime classes, or types like System.Task etc.) will need /// to use IDs that are all mutually disjoint. /// </summary> public readonly short DeclaringTypeId; public string? DeclaringTypeMetadataName { get { return DeclaringTypeId <= (int)SpecialType.Count ? ((SpecialType)DeclaringTypeId).GetMetadataName() : ((WellKnownType)DeclaringTypeId).GetMetadataName(); } } public readonly ushort Arity; public readonly string Name; /// <summary> /// Signature of the field or method, similar to metadata signature, /// but with the following exceptions: /// 1) Truncated on the left, for methods starts at [ParamCount], for fields at [Type] /// 2) Type tokens are not compressed /// 3) BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | I | U | Void types are encoded by /// using VALUETYPE+typeId notation. /// 4) array bounds are not included. /// 5) modifiers are not included. /// 6) (CLASS | VALUETYPE) are omitted after GENERICINST /// </summary> public readonly ImmutableArray<byte> Signature; /// <summary> /// Applicable only to properties and methods, throws otherwise. /// </summary> public int ParametersCount { get { MemberFlags memberKind = Flags & MemberFlags.KindMask; switch (memberKind) { case MemberFlags.Constructor: case MemberFlags.Method: case MemberFlags.PropertyGet: case MemberFlags.Property: return Signature[0]; default: throw ExceptionUtilities.UnexpectedValue(memberKind); } } } public MemberDescriptor( MemberFlags Flags, short DeclaringTypeId, string Name, ImmutableArray<byte> Signature, ushort Arity = 0) { this.Flags = Flags; this.DeclaringTypeId = DeclaringTypeId; this.Name = Name; this.Arity = Arity; this.Signature = Signature; } internal static ImmutableArray<MemberDescriptor> InitializeFromStream(Stream stream, string[] nameTable) { int count = nameTable.Length; var builder = ImmutableArray.CreateBuilder<MemberDescriptor>(count); var signatureBuilder = ImmutableArray.CreateBuilder<byte>(); for (int i = 0; i < count; i++) { MemberFlags flags = (MemberFlags)stream.ReadByte(); short declaringTypeId = ReadTypeId(stream); ushort arity = (ushort)stream.ReadByte(); if ((flags & MemberFlags.Field) != 0) { ParseType(signatureBuilder, stream); } else { // Property, PropertyGet, Method or Constructor ParseMethodOrPropertySignature(signatureBuilder, stream); } builder.Add(new MemberDescriptor(flags, declaringTypeId, nameTable[i], signatureBuilder.ToImmutable(), arity)); signatureBuilder.Clear(); } return builder.ToImmutable(); } /// <summary> /// The type Id may be: /// (1) encoded in a single byte (for types below 255) /// (2) encoded in two bytes (255 + extension byte) for types below 512 /// </summary> private static short ReadTypeId(Stream stream) { var firstByte = (byte)stream.ReadByte(); if (firstByte == (byte)WellKnownType.ExtSentinel) { return (short)(stream.ReadByte() + WellKnownType.ExtSentinel); } else { return firstByte; } } private static void ParseMethodOrPropertySignature(ImmutableArray<byte>.Builder builder, Stream stream) { int paramCount = stream.ReadByte(); builder.Add((byte)paramCount); // Return type ParseType(builder, stream, allowByRef: true); // Parameters for (int i = 0; i < paramCount; i++) { ParseType(builder, stream, allowByRef: true); } } private static void ParseType(ImmutableArray<byte>.Builder builder, Stream stream, bool allowByRef = false) { while (true) { var typeCode = (SignatureTypeCode)stream.ReadByte(); builder.Add((byte)typeCode); switch (typeCode) { default: throw ExceptionUtilities.UnexpectedValue(typeCode); case SignatureTypeCode.TypeHandle: ParseTypeHandle(builder, stream); return; case SignatureTypeCode.GenericTypeParameter: case SignatureTypeCode.GenericMethodParameter: builder.Add((byte)stream.ReadByte()); return; case SignatureTypeCode.ByReference: if (!allowByRef) goto default; break; case SignatureTypeCode.SZArray: break; case SignatureTypeCode.Pointer: break; case SignatureTypeCode.GenericTypeInstance: ParseGenericTypeInstance(builder, stream); return; } allowByRef = false; } } /// <summary> /// Read a type Id from the stream and copy it into the builder. /// This may copy one or two bytes depending on the first one. /// </summary> private static void ParseTypeHandle(ImmutableArray<byte>.Builder builder, Stream stream) { var firstByte = (byte)stream.ReadByte(); builder.Add(firstByte); if (firstByte == (byte)WellKnownType.ExtSentinel) { var secondByte = (byte)stream.ReadByte(); builder.Add(secondByte); } } private static void ParseGenericTypeInstance(ImmutableArray<byte>.Builder builder, Stream stream) { ParseType(builder, stream); // Generic type parameters int argumentCount = stream.ReadByte(); builder.Add((byte)argumentCount); for (int i = 0; i < argumentCount; i++) { ParseType(builder, stream); } } } }
-1