repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/System.Text/Utf16Utility.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // <auto-generated/> #nullable disable // Copied from https://github.com/dotnet/runtime/blob/c73774b53944a6007ee85f138e3ff3d3297846ea/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.cs#L1 // So that we can use Runes in netstandard 2.0 #if !NETCOREAPP using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.Text.Unicode { internal static partial class Utf16Utility { /// <summary> /// Returns true iff the UInt32 represents two ASCII UTF-16 characters in machine endianness. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt32AreAscii(uint value) { return (value & ~0x007F_007Fu) == 0; } /// <summary> /// Returns true iff the UInt64 represents four ASCII UTF-16 characters in machine endianness. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt64AreAscii(ulong value) { return (value & ~0x007F_007F_007F_007Ful) == 0; } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant /// lowercase representation of those characters. Requires the input value to contain /// two ASCII UTF-16 characters in machine endianness. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToLowercase(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z' uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); // the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'A' and <= 'Z' uint mask = (combinedIndicator & 0x0080_0080u) >> 2; return value ^ mask; // bit flip uppercase letters [A-Z] => [a-z] } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant /// uppercase representation of those characters. Requires the input value to contain /// two ASCII UTF-16 characters in machine endianness. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToUppercase(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a' uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z' uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); // the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'a' and <= 'z' uint mask = (combinedIndicator & 0x0080_0080u) >> 2; return value ^ mask; // bit flip lowercase letters [a-z] => [A-Z] } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff /// the input contains one or more lowercase ASCII characters. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyLowercaseAsciiChar(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a' uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z' uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); return (combinedIndicator & 0x0080_0080u) != 0; } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff /// the input contains one or more uppercase ASCII characters. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyUppercaseAsciiChar(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z' uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); return (combinedIndicator & 0x0080_0080u) != 0; } /// <summary> /// Given two UInt32s that represent two ASCII UTF-16 characters each, returns true iff /// the two inputs are equal using an ordinal case-insensitive comparison. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32OrdinalIgnoreCaseAscii(uint valueA, uint valueB) { // ASSUMPTION: Caller has validated that input values are ASCII. Debug.Assert(AllCharsInUInt32AreAscii(valueA)); Debug.Assert(AllCharsInUInt32AreAscii(valueB)); // a mask of all bits which are different between A and B uint differentBits = valueA ^ valueB; // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value < 'A' uint lowerIndicator = valueA + 0x0100_0100u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value > 'z' uint upperIndicator = (valueA | 0x0020_0020u) + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word is *not* [A-Za-z] uint combinedIndicator = lowerIndicator | upperIndicator; // Shift all the 0x80 bits of 'combinedIndicator' into the 0x20 positions, then set all bits // aside from 0x20. This creates a mask where all bits are set *except* for the 0x20 bits // which correspond to alpha chars (either lower or upper). For these alpha chars only, the // 0x20 bit is allowed to differ between the two input values. Every other char must be an // exact bitwise match between the two input values. In other words, (valueA & mask) will // convert valueA to uppercase, so (valueA & mask) == (valueB & mask) answers "is the uppercase // form of valueA equal to the uppercase form of valueB?" (Technically if valueA has an alpha // char in the same position as a non-alpha char in valueB, or vice versa, this operation will // result in nonsense, but it'll still compute as inequal regardless, which is what we want ultimately.) // The line below is a more efficient way of doing the same check taking advantage of the XOR // computation we performed at the beginning of the method. return (((combinedIndicator >> 2) | ~0x0020_0020u) & differentBits) == 0; } /// <summary> /// Given two UInt64s that represent four ASCII UTF-16 characters each, returns true iff /// the two inputs are equal using an ordinal case-insensitive comparison. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt64OrdinalIgnoreCaseAscii(ulong valueA, ulong valueB) { // ASSUMPTION: Caller has validated that input values are ASCII. Debug.Assert(AllCharsInUInt64AreAscii(valueA)); Debug.Assert(AllCharsInUInt64AreAscii(valueB)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' ulong lowerIndicator = valueA + 0x0080_0080_0080_0080ul - 0x0041_0041_0041_0041ul; // the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value <= 'z' ulong upperIndicator = (valueA | 0x0020_0020_0020_0020ul) + 0x0100_0100_0100_0100ul - 0x007B_007B_007B_007Bul; // the 0x20 bit of each word of 'combinedIndicator' will be set iff the word is [A-Za-z] ulong combinedIndicator = (0x0080_0080_0080_0080ul & lowerIndicator & upperIndicator) >> 2; // Convert both values to lowercase (using the combined indicator from the first value) // and compare for equality. It's possible that the first value will contain an alpha character // where the second value doesn't (or vice versa), and applying the combined indicator will // create nonsensical data, but the comparison would have failed anyway in this case so it's // a safe operation to perform. // // This 64-bit method is similar to the 32-bit method, but it performs the equivalent of convert-to- // lowercase-then-compare rather than convert-to-uppercase-and-compare. This particular operation // happens to be faster on x64. return (valueA | combinedIndicator) == (valueB | combinedIndicator); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // <auto-generated/> #nullable disable // Copied from https://github.com/dotnet/runtime/blob/c73774b53944a6007ee85f138e3ff3d3297846ea/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf16Utility.cs#L1 // So that we can use Runes in netstandard 2.0 #if !NETCOREAPP using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.Text.Unicode { internal static partial class Utf16Utility { /// <summary> /// Returns true iff the UInt32 represents two ASCII UTF-16 characters in machine endianness. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt32AreAscii(uint value) { return (value & ~0x007F_007Fu) == 0; } /// <summary> /// Returns true iff the UInt64 represents four ASCII UTF-16 characters in machine endianness. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt64AreAscii(ulong value) { return (value & ~0x007F_007F_007F_007Ful) == 0; } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant /// lowercase representation of those characters. Requires the input value to contain /// two ASCII UTF-16 characters in machine endianness. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToLowercase(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z' uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); // the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'A' and <= 'Z' uint mask = (combinedIndicator & 0x0080_0080u) >> 2; return value ^ mask; // bit flip uppercase letters [A-Z] => [a-z] } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns the invariant /// uppercase representation of those characters. Requires the input value to contain /// two ASCII UTF-16 characters in machine endianness. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToUppercase(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a' uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z' uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); // the 0x20 bit of each word of 'mask' will be set iff the word has value >= 'a' and <= 'z' uint mask = (combinedIndicator & 0x0080_0080u) >> 2; return value ^ mask; // bit flip lowercase letters [a-z] => [A-Z] } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff /// the input contains one or more lowercase ASCII characters. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyLowercaseAsciiChar(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'a' uint lowerIndicator = value + 0x0080_0080u - 0x0061_0061u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'z' uint upperIndicator = value + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'a' and <= 'z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); return (combinedIndicator & 0x0080_0080u) != 0; } /// <summary> /// Given a UInt32 that represents two ASCII UTF-16 characters, returns true iff /// the input contains one or more uppercase ASCII characters. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyUppercaseAsciiChar(uint value) { // ASSUMPTION: Caller has validated that input value is ASCII. Debug.Assert(AllCharsInUInt32AreAscii(value)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' uint lowerIndicator = value + 0x0080_0080u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff the word has value > 'Z' uint upperIndicator = value + 0x0080_0080u - 0x005B_005Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word has value >= 'A' and <= 'Z' uint combinedIndicator = (lowerIndicator ^ upperIndicator); return (combinedIndicator & 0x0080_0080u) != 0; } /// <summary> /// Given two UInt32s that represent two ASCII UTF-16 characters each, returns true iff /// the two inputs are equal using an ordinal case-insensitive comparison. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32OrdinalIgnoreCaseAscii(uint valueA, uint valueB) { // ASSUMPTION: Caller has validated that input values are ASCII. Debug.Assert(AllCharsInUInt32AreAscii(valueA)); Debug.Assert(AllCharsInUInt32AreAscii(valueB)); // a mask of all bits which are different between A and B uint differentBits = valueA ^ valueB; // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value < 'A' uint lowerIndicator = valueA + 0x0100_0100u - 0x0041_0041u; // the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value > 'z' uint upperIndicator = (valueA | 0x0020_0020u) + 0x0080_0080u - 0x007B_007Bu; // the 0x80 bit of each word of 'combinedIndicator' will be set iff the word is *not* [A-Za-z] uint combinedIndicator = lowerIndicator | upperIndicator; // Shift all the 0x80 bits of 'combinedIndicator' into the 0x20 positions, then set all bits // aside from 0x20. This creates a mask where all bits are set *except* for the 0x20 bits // which correspond to alpha chars (either lower or upper). For these alpha chars only, the // 0x20 bit is allowed to differ between the two input values. Every other char must be an // exact bitwise match between the two input values. In other words, (valueA & mask) will // convert valueA to uppercase, so (valueA & mask) == (valueB & mask) answers "is the uppercase // form of valueA equal to the uppercase form of valueB?" (Technically if valueA has an alpha // char in the same position as a non-alpha char in valueB, or vice versa, this operation will // result in nonsense, but it'll still compute as inequal regardless, which is what we want ultimately.) // The line below is a more efficient way of doing the same check taking advantage of the XOR // computation we performed at the beginning of the method. return (((combinedIndicator >> 2) | ~0x0020_0020u) & differentBits) == 0; } /// <summary> /// Given two UInt64s that represent four ASCII UTF-16 characters each, returns true iff /// the two inputs are equal using an ordinal case-insensitive comparison. /// </summary> /// <remarks> /// This is a branchless implementation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt64OrdinalIgnoreCaseAscii(ulong valueA, ulong valueB) { // ASSUMPTION: Caller has validated that input values are ASCII. Debug.Assert(AllCharsInUInt64AreAscii(valueA)); Debug.Assert(AllCharsInUInt64AreAscii(valueB)); // the 0x80 bit of each word of 'lowerIndicator' will be set iff the word has value >= 'A' ulong lowerIndicator = valueA + 0x0080_0080_0080_0080ul - 0x0041_0041_0041_0041ul; // the 0x80 bit of each word of 'upperIndicator' will be set iff (word | 0x20) has value <= 'z' ulong upperIndicator = (valueA | 0x0020_0020_0020_0020ul) + 0x0100_0100_0100_0100ul - 0x007B_007B_007B_007Bul; // the 0x20 bit of each word of 'combinedIndicator' will be set iff the word is [A-Za-z] ulong combinedIndicator = (0x0080_0080_0080_0080ul & lowerIndicator & upperIndicator) >> 2; // Convert both values to lowercase (using the combined indicator from the first value) // and compare for equality. It's possible that the first value will contain an alpha character // where the second value doesn't (or vice versa), and applying the combined indicator will // create nonsensical data, but the comparison would have failed anyway in this case so it's // a safe operation to perform. // // This 64-bit method is similar to the 32-bit method, but it performs the equivalent of convert-to- // lowercase-then-compare rather than convert-to-uppercase-and-compare. This particular operation // happens to be faster on x64. return (valueA | combinedIndicator) == (valueB | combinedIndicator); } } } #endif
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Test/PdbUtilities/HResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Test.Utilities { public static class HResult { public const int S_OK = 0x0; public const int S_FALSE = 0x1; public const int E_FAIL = unchecked((int)0x80004005); public const int E_NOTIMPL = unchecked((int)0x80004001); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Test.Utilities { public static class HResult { public const int S_OK = 0x0; public const int S_FALSE = 0x1; public const int E_FAIL = unchecked((int)0x80004005); public const int E_NOTIMPL = unchecked((int)0x80004001); } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SQLite.Interop; using Roslyn.Utilities; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.v2.Interop { using static SQLitePersistentStorageConstants; /// <summary> /// Encapsulates a connection to a sqlite database. On construction an attempt will be made /// to open the DB if it exists, or create it if it does not. /// /// Connections are considered relatively heavyweight and are pooled until the <see cref="SQLitePersistentStorage"/> /// is <see cref="SQLitePersistentStorage.Dispose"/>d. Connections can be used by different threads, /// but only as long as they are used by one thread at a time. They are not safe for concurrent /// use by several threads. /// /// <see cref="SqlStatement"/>s can be created through the user of <see cref="GetResettableStatement"/>. /// These statements are cached for the lifetime of the connection and are only finalized /// (i.e. destroyed) when the connection is closed. /// </summary> internal class SqlConnection { // Cached utf8 (and null terminated) versions of the common strings we need to pass to sqlite. Used to prevent // having to convert these names to/from utf16 to utf8 on every call. Sqlite requires these be null terminated. private static readonly byte[] s_mainNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.Main.GetName()); private static readonly byte[] s_writeCacheNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.WriteCache.GetName()); private static readonly byte[] s_solutionTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(SolutionDataTableName); private static readonly byte[] s_projectTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ProjectDataTableName); private static readonly byte[] s_documentTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DocumentDataTableName); private static readonly byte[] s_checksumColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ChecksumColumnName); private static readonly byte[] s_dataColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DataColumnName); private static byte[] GetUtf8BytesWithTrailingZero(string value) { var length = Encoding.UTF8.GetByteCount(value); // Add one for the trailing zero. var byteArray = new byte[length + 1]; var wrote = Encoding.UTF8.GetBytes(value, 0, value.Length, byteArray, 0); Contract.ThrowIfFalse(wrote == length); // Paranoia, but write in the trailing zero no matter what. byteArray[^1] = 0; return byteArray; } /// <summary> /// The raw handle to the underlying DB. /// </summary> private readonly SafeSqliteHandle _handle; /// <summary> /// Our cache of prepared statements for given sql strings. /// </summary> private readonly Dictionary<string, SqlStatement> _queryToStatement; /// <summary> /// Whether or not we're in a transaction. We currently don't supported nested transactions. /// If we want that, we can achieve it through sqlite "save points". However, that's adds a /// lot of complexity that is nice to avoid. /// </summary> public bool IsInTransaction { get; private set; } public static SqlConnection Create(IPersistentStorageFaultInjector? faultInjector, string databasePath) { faultInjector?.OnNewConnection(); // Allocate dictionary before doing any sqlite work. That way if it throws // we don't have to do any additional cleanup. var queryToStatement = new Dictionary<string, SqlStatement>(); // Use SQLITE_OPEN_NOMUTEX to enable multi-thread mode, where multiple connections can // be used provided each one is only used from a single thread at a time. // // Use SHAREDCACHE so that we can have an in-memory DB that we dump our writes into. We // need SHAREDCACHE so that all connections see that same in-memory DB. This also // requires OPEN_URI since we need a `file::memory:` uri for them all to refer to. // // see https://sqlite.org/threadsafe.html for more detail var flags = OpenFlags.SQLITE_OPEN_CREATE | OpenFlags.SQLITE_OPEN_READWRITE | OpenFlags.SQLITE_OPEN_NOMUTEX | OpenFlags.SQLITE_OPEN_SHAREDCACHE | OpenFlags.SQLITE_OPEN_URI; var handle = NativeMethods.sqlite3_open_v2(databasePath, (int)flags, vfs: null, out var result); if (result != Result.OK) { handle.Dispose(); throw new SqlException(result, $"Could not open database file: {databasePath} ({result})"); } try { NativeMethods.sqlite3_busy_timeout(handle, (int)TimeSpan.FromMinutes(1).TotalMilliseconds); var connection = new SqlConnection(handle, queryToStatement); // Attach (creating if necessary) a singleton in-memory write cache to this connection. // // From: https://www.sqlite.org/sharedcache.html Enabling shared-cache for an in-memory database allows // two or more database connections in the same process to have access to the same in-memory database. // An in-memory database in shared cache is automatically deleted and memory is reclaimed when the last // connection to that database closes. // Using `?mode=memory&cache=shared as writecache` at the end ensures all connections (to the on-disk // db) see the same db (https://sqlite.org/inmemorydb.html) and the same data when reading and writing. // i.e. if one connection writes data to this, another connection will see that data when reading. // Without this, each connection would get their own private memory db independent of all other // connections. // Workaround https://github.com/ericsink/SQLitePCL.raw/issues/407. On non-windows do not pass in the // uri of the DB on disk we're associating this in-memory cache with. This throws on at least OSX for // reasons that aren't fully understood yet. If more details/fixes emerge in that linked issue, we can // ideally remove this and perform the attachment uniformly on all platforms. var attachString = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"attach database '{new Uri(databasePath).AbsoluteUri}?mode=memory&cache=shared' as {Database.WriteCache.GetName()};" : $"attach database 'file::memory:?cache=shared' as {Database.WriteCache.GetName()};"; connection.ExecuteCommand(attachString); return connection; } catch { // If we failed to create connection, ensure that we still release the sqlite // handle. handle.Dispose(); throw; } } private SqlConnection(SafeSqliteHandle handle, Dictionary<string, SqlStatement> queryToStatement) { _handle = handle; _queryToStatement = queryToStatement; } internal void Close_OnlyForUseBySQLiteConnectionPool() { // Dispose of the underlying handle at the end of cleanup using var _ = _handle; // release all the cached statements we have. // // use the struct-enumerator of our dictionary to prevent any allocations here. We // don't want to risk an allocation causing an OOM which prevents executing the // following cleanup code. foreach (var (_, statement) in _queryToStatement) { statement.Close_OnlyForUseBySqlConnection(); } _queryToStatement.Clear(); } public void ExecuteCommand(string command, bool throwOnError = true) { using var resettableStatement = GetResettableStatement(command); var statement = resettableStatement.Statement; var result = statement.Step(throwOnError); if (result != Result.DONE && throwOnError) { Throw(result); } } public ResettableSqlStatement GetResettableStatement(string query) { if (!_queryToStatement.TryGetValue(query, out var statement)) { var handle = NativeMethods.sqlite3_prepare_v2(_handle, query, out var result); try { ThrowIfNotOk(result); statement = new SqlStatement(this, handle); _queryToStatement[query] = statement; } catch { handle.Dispose(); throw; } } return new ResettableSqlStatement(statement); } public void RunInTransaction<TState>(Action<TState> action, TState state) { RunInTransaction( static state => { state.action(state.state); return (object?)null; }, (action, state)); } public TResult RunInTransaction<TState, TResult>(Func<TState, TResult> action, TState state) { try { if (IsInTransaction) { throw new InvalidOperationException("Nested transactions not currently supported"); } IsInTransaction = true; ExecuteCommand("begin transaction"); var result = action(state); ExecuteCommand("commit transaction"); return result; } catch (SqlException ex) when (ex.Result == Result.FULL || ex.Result == Result.IOERR || ex.Result == Result.BUSY || ex.Result == Result.LOCKED || ex.Result == Result.NOMEM) { // See documentation here: https://sqlite.org/lang_transaction.html // If certain kinds of errors occur within a transaction, the transaction // may or may not be rolled back automatically. The errors that can cause // an automatic rollback include: // SQLITE_FULL: database or disk full // SQLITE_IOERR: disk I/ O error // SQLITE_BUSY: database in use by another process // SQLITE_LOCKED: database in use by another connection in the same process // SQLITE_NOMEM: out or memory // It is recommended that applications respond to the errors listed above by // explicitly issuing a ROLLBACK command. If the transaction has already been // rolled back automatically by the error response, then the ROLLBACK command // will fail with an error, but no harm is caused by this. Rollback(throwOnError: false); throw; } catch (Exception) { Rollback(throwOnError: true); throw; } finally { IsInTransaction = false; } } private void Rollback(bool throwOnError) => ExecuteCommand("rollback transaction", throwOnError); public int LastInsertRowId() => (int)NativeMethods.sqlite3_last_insert_rowid(_handle); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Stream> ReadDataBlob_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Data, rowId, static (self, blobHandle) => new Optional<Stream>(self.ReadBlob(blobHandle))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Checksum.HashData> ReadChecksum_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Checksum, rowId, static (self, blobHandle) => { // If the length of the blob isn't correct, then we can't read a checksum out of this. var length = NativeMethods.sqlite3_blob_bytes(blobHandle); if (length != Checksum.HashSize) return new Optional<Checksum.HashData>(); Span<byte> bytes = stackalloc byte[Checksum.HashSize]; self.ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blobHandle, bytes, offset: 0)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(bytes, out Checksum.HashData result)); return new Optional<Checksum.HashData>(result); }); } private Stream ReadBlob(SafeSqliteBlobHandle blob) { var length = NativeMethods.sqlite3_blob_bytes(blob); // If it's a small blob, just read it into one of our pooled arrays, and then // create a PooledStream over it. if (length <= SQLitePersistentStorage.MaxPooledByteArrayLength) { return ReadBlobIntoPooledStream(blob, length); } else { // Otherwise, it's a large stream. Just take the hit of allocating. var bytes = new byte[length]; ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, bytes.AsSpan(), offset: 0)); return new MemoryStream(bytes); } } private Stream ReadBlobIntoPooledStream(SafeSqliteBlobHandle blob, int length) { var bytes = SQLitePersistentStorage.GetPooledBytes(); try { ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, new Span<byte>(bytes, start: 0, length), offset: 0)); // Copy those bytes into a pooled stream return SerializableBytes.CreateReadableStream(bytes, length); } finally { // Return our small array back to the pool. SQLitePersistentStorage.ReturnPooledBytes(bytes); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<T> ReadBlob_MustRunInTransaction<T>( Database database, Table table, Column column, long rowId, Func<SqlConnection, SafeSqliteBlobHandle, Optional<T>> readBlob) { // NOTE: we do need to do the blob reading in a transaction because of the // following: https://www.sqlite.org/c3ref/blob_open.html // // If the row that a BLOB handle points to is modified by an UPDATE, DELETE, // or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". // This is true if any column of the row is changed, even a column other than // the one the BLOB handle is open on. Calls to sqlite3_blob_read() and // sqlite3_blob_write() for an expired BLOB handle fail with a return code of // SQLITE_ABORT. if (!IsInTransaction) { throw new InvalidOperationException("Must read blobs within a transaction to prevent corruption!"); } var databaseNameBytes = database switch { Database.Main => s_mainNameWithTrailingZero, Database.WriteCache => s_writeCacheNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(database), }; var tableNameBytes = table switch { Table.Solution => s_solutionTableNameWithTrailingZero, Table.Project => s_projectTableNameWithTrailingZero, Table.Document => s_documentTableNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(table), }; var columnNameBytes = column switch { Column.Data => s_dataColumnNameWithTrailingZero, Column.Checksum => s_checksumColumnNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(column), }; unsafe { fixed (byte* databaseNamePtr = databaseNameBytes) fixed (byte* tableNamePtr = tableNameBytes) fixed (byte* columnNamePtr = columnNameBytes) { // sqlite requires a byte* and a length *not* including the trailing zero. So subtract one from all // the array lengths to get the length they expect. const int ReadOnlyFlags = 0; using var blob = NativeMethods.sqlite3_blob_open( _handle, utf8z.FromPtrLen(databaseNamePtr, databaseNameBytes.Length - 1), utf8z.FromPtrLen(tableNamePtr, tableNameBytes.Length - 1), utf8z.FromPtrLen(columnNamePtr, columnNameBytes.Length - 1), rowId, ReadOnlyFlags, out var result); if (result == Result.ERROR) { // can happen when rowId points to a row that hasn't been written to yet. return default; } ThrowIfNotOk(result); return readBlob(this, blob); } } } public void ThrowIfNotOk(int result) => ThrowIfNotOk((Result)result); public void ThrowIfNotOk(Result result) => ThrowIfNotOk(_handle, result); public static void ThrowIfNotOk(SafeSqliteHandle handle, Result result) { if (result != Result.OK) { Throw(handle, result); } } public void Throw(Result result) => Throw(_handle, result); public static void Throw(SafeSqliteHandle handle, Result result) => throw new SqlException(result, NativeMethods.sqlite3_errmsg(handle) + Environment.NewLine + NativeMethods.sqlite3_errstr(NativeMethods.sqlite3_extended_errcode(handle))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SQLite.Interop; using Roslyn.Utilities; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.v2.Interop { using static SQLitePersistentStorageConstants; /// <summary> /// Encapsulates a connection to a sqlite database. On construction an attempt will be made /// to open the DB if it exists, or create it if it does not. /// /// Connections are considered relatively heavyweight and are pooled until the <see cref="SQLitePersistentStorage"/> /// is <see cref="SQLitePersistentStorage.Dispose"/>d. Connections can be used by different threads, /// but only as long as they are used by one thread at a time. They are not safe for concurrent /// use by several threads. /// /// <see cref="SqlStatement"/>s can be created through the user of <see cref="GetResettableStatement"/>. /// These statements are cached for the lifetime of the connection and are only finalized /// (i.e. destroyed) when the connection is closed. /// </summary> internal class SqlConnection { // Cached utf8 (and null terminated) versions of the common strings we need to pass to sqlite. Used to prevent // having to convert these names to/from utf16 to utf8 on every call. Sqlite requires these be null terminated. private static readonly byte[] s_mainNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.Main.GetName()); private static readonly byte[] s_writeCacheNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.WriteCache.GetName()); private static readonly byte[] s_solutionTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(SolutionDataTableName); private static readonly byte[] s_projectTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ProjectDataTableName); private static readonly byte[] s_documentTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DocumentDataTableName); private static readonly byte[] s_checksumColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ChecksumColumnName); private static readonly byte[] s_dataColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DataColumnName); private static byte[] GetUtf8BytesWithTrailingZero(string value) { var length = Encoding.UTF8.GetByteCount(value); // Add one for the trailing zero. var byteArray = new byte[length + 1]; var wrote = Encoding.UTF8.GetBytes(value, 0, value.Length, byteArray, 0); Contract.ThrowIfFalse(wrote == length); // Paranoia, but write in the trailing zero no matter what. byteArray[^1] = 0; return byteArray; } /// <summary> /// The raw handle to the underlying DB. /// </summary> private readonly SafeSqliteHandle _handle; /// <summary> /// Our cache of prepared statements for given sql strings. /// </summary> private readonly Dictionary<string, SqlStatement> _queryToStatement; /// <summary> /// Whether or not we're in a transaction. We currently don't supported nested transactions. /// If we want that, we can achieve it through sqlite "save points". However, that's adds a /// lot of complexity that is nice to avoid. /// </summary> public bool IsInTransaction { get; private set; } public static SqlConnection Create(IPersistentStorageFaultInjector? faultInjector, string databasePath) { faultInjector?.OnNewConnection(); // Allocate dictionary before doing any sqlite work. That way if it throws // we don't have to do any additional cleanup. var queryToStatement = new Dictionary<string, SqlStatement>(); // Use SQLITE_OPEN_NOMUTEX to enable multi-thread mode, where multiple connections can // be used provided each one is only used from a single thread at a time. // // Use SHAREDCACHE so that we can have an in-memory DB that we dump our writes into. We // need SHAREDCACHE so that all connections see that same in-memory DB. This also // requires OPEN_URI since we need a `file::memory:` uri for them all to refer to. // // see https://sqlite.org/threadsafe.html for more detail var flags = OpenFlags.SQLITE_OPEN_CREATE | OpenFlags.SQLITE_OPEN_READWRITE | OpenFlags.SQLITE_OPEN_NOMUTEX | OpenFlags.SQLITE_OPEN_SHAREDCACHE | OpenFlags.SQLITE_OPEN_URI; var handle = NativeMethods.sqlite3_open_v2(databasePath, (int)flags, vfs: null, out var result); if (result != Result.OK) { handle.Dispose(); throw new SqlException(result, $"Could not open database file: {databasePath} ({result})"); } try { NativeMethods.sqlite3_busy_timeout(handle, (int)TimeSpan.FromMinutes(1).TotalMilliseconds); var connection = new SqlConnection(handle, queryToStatement); // Attach (creating if necessary) a singleton in-memory write cache to this connection. // // From: https://www.sqlite.org/sharedcache.html Enabling shared-cache for an in-memory database allows // two or more database connections in the same process to have access to the same in-memory database. // An in-memory database in shared cache is automatically deleted and memory is reclaimed when the last // connection to that database closes. // Using `?mode=memory&cache=shared as writecache` at the end ensures all connections (to the on-disk // db) see the same db (https://sqlite.org/inmemorydb.html) and the same data when reading and writing. // i.e. if one connection writes data to this, another connection will see that data when reading. // Without this, each connection would get their own private memory db independent of all other // connections. // Workaround https://github.com/ericsink/SQLitePCL.raw/issues/407. On non-windows do not pass in the // uri of the DB on disk we're associating this in-memory cache with. This throws on at least OSX for // reasons that aren't fully understood yet. If more details/fixes emerge in that linked issue, we can // ideally remove this and perform the attachment uniformly on all platforms. var attachString = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"attach database '{new Uri(databasePath).AbsoluteUri}?mode=memory&cache=shared' as {Database.WriteCache.GetName()};" : $"attach database 'file::memory:?cache=shared' as {Database.WriteCache.GetName()};"; connection.ExecuteCommand(attachString); return connection; } catch { // If we failed to create connection, ensure that we still release the sqlite // handle. handle.Dispose(); throw; } } private SqlConnection(SafeSqliteHandle handle, Dictionary<string, SqlStatement> queryToStatement) { _handle = handle; _queryToStatement = queryToStatement; } internal void Close_OnlyForUseBySQLiteConnectionPool() { // Dispose of the underlying handle at the end of cleanup using var _ = _handle; // release all the cached statements we have. // // use the struct-enumerator of our dictionary to prevent any allocations here. We // don't want to risk an allocation causing an OOM which prevents executing the // following cleanup code. foreach (var (_, statement) in _queryToStatement) { statement.Close_OnlyForUseBySqlConnection(); } _queryToStatement.Clear(); } public void ExecuteCommand(string command, bool throwOnError = true) { using var resettableStatement = GetResettableStatement(command); var statement = resettableStatement.Statement; var result = statement.Step(throwOnError); if (result != Result.DONE && throwOnError) { Throw(result); } } public ResettableSqlStatement GetResettableStatement(string query) { if (!_queryToStatement.TryGetValue(query, out var statement)) { var handle = NativeMethods.sqlite3_prepare_v2(_handle, query, out var result); try { ThrowIfNotOk(result); statement = new SqlStatement(this, handle); _queryToStatement[query] = statement; } catch { handle.Dispose(); throw; } } return new ResettableSqlStatement(statement); } public void RunInTransaction<TState>(Action<TState> action, TState state) { RunInTransaction( static state => { state.action(state.state); return (object?)null; }, (action, state)); } public TResult RunInTransaction<TState, TResult>(Func<TState, TResult> action, TState state) { try { if (IsInTransaction) { throw new InvalidOperationException("Nested transactions not currently supported"); } IsInTransaction = true; ExecuteCommand("begin transaction"); var result = action(state); ExecuteCommand("commit transaction"); return result; } catch (SqlException ex) when (ex.Result == Result.FULL || ex.Result == Result.IOERR || ex.Result == Result.BUSY || ex.Result == Result.LOCKED || ex.Result == Result.NOMEM) { // See documentation here: https://sqlite.org/lang_transaction.html // If certain kinds of errors occur within a transaction, the transaction // may or may not be rolled back automatically. The errors that can cause // an automatic rollback include: // SQLITE_FULL: database or disk full // SQLITE_IOERR: disk I/ O error // SQLITE_BUSY: database in use by another process // SQLITE_LOCKED: database in use by another connection in the same process // SQLITE_NOMEM: out or memory // It is recommended that applications respond to the errors listed above by // explicitly issuing a ROLLBACK command. If the transaction has already been // rolled back automatically by the error response, then the ROLLBACK command // will fail with an error, but no harm is caused by this. Rollback(throwOnError: false); throw; } catch (Exception) { Rollback(throwOnError: true); throw; } finally { IsInTransaction = false; } } private void Rollback(bool throwOnError) => ExecuteCommand("rollback transaction", throwOnError); public int LastInsertRowId() => (int)NativeMethods.sqlite3_last_insert_rowid(_handle); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Stream> ReadDataBlob_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Data, rowId, static (self, blobHandle) => new Optional<Stream>(self.ReadBlob(blobHandle))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Checksum.HashData> ReadChecksum_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Checksum, rowId, static (self, blobHandle) => { // If the length of the blob isn't correct, then we can't read a checksum out of this. var length = NativeMethods.sqlite3_blob_bytes(blobHandle); if (length != Checksum.HashSize) return new Optional<Checksum.HashData>(); Span<byte> bytes = stackalloc byte[Checksum.HashSize]; self.ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blobHandle, bytes, offset: 0)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(bytes, out Checksum.HashData result)); return new Optional<Checksum.HashData>(result); }); } private Stream ReadBlob(SafeSqliteBlobHandle blob) { var length = NativeMethods.sqlite3_blob_bytes(blob); // If it's a small blob, just read it into one of our pooled arrays, and then // create a PooledStream over it. if (length <= SQLitePersistentStorage.MaxPooledByteArrayLength) { return ReadBlobIntoPooledStream(blob, length); } else { // Otherwise, it's a large stream. Just take the hit of allocating. var bytes = new byte[length]; ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, bytes.AsSpan(), offset: 0)); return new MemoryStream(bytes); } } private Stream ReadBlobIntoPooledStream(SafeSqliteBlobHandle blob, int length) { var bytes = SQLitePersistentStorage.GetPooledBytes(); try { ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, new Span<byte>(bytes, start: 0, length), offset: 0)); // Copy those bytes into a pooled stream return SerializableBytes.CreateReadableStream(bytes, length); } finally { // Return our small array back to the pool. SQLitePersistentStorage.ReturnPooledBytes(bytes); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<T> ReadBlob_MustRunInTransaction<T>( Database database, Table table, Column column, long rowId, Func<SqlConnection, SafeSqliteBlobHandle, Optional<T>> readBlob) { // NOTE: we do need to do the blob reading in a transaction because of the // following: https://www.sqlite.org/c3ref/blob_open.html // // If the row that a BLOB handle points to is modified by an UPDATE, DELETE, // or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". // This is true if any column of the row is changed, even a column other than // the one the BLOB handle is open on. Calls to sqlite3_blob_read() and // sqlite3_blob_write() for an expired BLOB handle fail with a return code of // SQLITE_ABORT. if (!IsInTransaction) { throw new InvalidOperationException("Must read blobs within a transaction to prevent corruption!"); } var databaseNameBytes = database switch { Database.Main => s_mainNameWithTrailingZero, Database.WriteCache => s_writeCacheNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(database), }; var tableNameBytes = table switch { Table.Solution => s_solutionTableNameWithTrailingZero, Table.Project => s_projectTableNameWithTrailingZero, Table.Document => s_documentTableNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(table), }; var columnNameBytes = column switch { Column.Data => s_dataColumnNameWithTrailingZero, Column.Checksum => s_checksumColumnNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(column), }; unsafe { fixed (byte* databaseNamePtr = databaseNameBytes) fixed (byte* tableNamePtr = tableNameBytes) fixed (byte* columnNamePtr = columnNameBytes) { // sqlite requires a byte* and a length *not* including the trailing zero. So subtract one from all // the array lengths to get the length they expect. const int ReadOnlyFlags = 0; using var blob = NativeMethods.sqlite3_blob_open( _handle, utf8z.FromPtrLen(databaseNamePtr, databaseNameBytes.Length - 1), utf8z.FromPtrLen(tableNamePtr, tableNameBytes.Length - 1), utf8z.FromPtrLen(columnNamePtr, columnNameBytes.Length - 1), rowId, ReadOnlyFlags, out var result); if (result == Result.ERROR) { // can happen when rowId points to a row that hasn't been written to yet. return default; } ThrowIfNotOk(result); return readBlob(this, blob); } } } public void ThrowIfNotOk(int result) => ThrowIfNotOk((Result)result); public void ThrowIfNotOk(Result result) => ThrowIfNotOk(_handle, result); public static void ThrowIfNotOk(SafeSqliteHandle handle, Result result) { if (result != Result.OK) { Throw(handle, result); } } public void Throw(Result result) => Throw(_handle, result); public static void Throw(SafeSqliteHandle handle, Result result) => throw new SqlException(result, NativeMethods.sqlite3_errmsg(handle) + Environment.NewLine + NativeMethods.sqlite3_errstr(NativeMethods.sqlite3_extended_errcode(handle))); } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTokenExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal static partial class SyntaxTokenExtensions { public static bool IsUsingOrExternKeyword(this SyntaxToken token) { return token.Kind() == SyntaxKind.UsingKeyword || token.Kind() == SyntaxKind.ExternKeyword; } public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token) { if (token.IsKind(SyntaxKind.UsingKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.UsingKeyword == token) { return true; } } return false; } public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token) { if (token.IsKind(SyntaxKind.StaticKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.StaticKeyword == token) { return true; } } return false; } public static bool IsBeginningOfStatementContext(this SyntaxToken token) { // cases: // { // | // } // | // Note, the following is *not* a legal statement context: // do { } | // ...; // | // case 0: // | // default: // | // label: // | // if (goo) // | // while (true) // | // do // | // for (;;) // | // foreach (var v in c) // | // else // | // using (expr) // | // fixed (void* v = &expr) // | // lock (expr) // | // for ( ; ; Goo(), | // After attribute lists on a statement: // [Bar] // | switch (token.Kind()) { case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block): return true; case SyntaxKind.SemicolonToken: var statement = token.GetAncestor<StatementSyntax>(); return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) && statement.GetLastToken(includeZeroWidth: true) == token; case SyntaxKind.CloseBraceToken: if (token.Parent.IsKind(SyntaxKind.Block)) { if (token.Parent.Parent is StatementSyntax) { // Most blocks that are the child of statement are places // that we can follow with another statement. i.e.: // if { } // while () { } // There are two exceptions. // try {} // do {} if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) && !token.Parent.IsParentKind(SyntaxKind.DoStatement)) { return true; } } else if ( token.Parent.IsParentKind(SyntaxKind.ElseClause) || token.Parent.IsParentKind(SyntaxKind.FinallyClause) || token.Parent.IsParentKind(SyntaxKind.CatchClause) || token.Parent.IsParentKind(SyntaxKind.SwitchSection)) { return true; } } if (token.Parent.IsKind(SyntaxKind.SwitchStatement)) { return true; } return false; case SyntaxKind.ColonToken: return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel, SyntaxKind.LabeledStatement); case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement): return true; case SyntaxKind.CloseParenToken: var parent = token.Parent; return parent.IsKind(SyntaxKind.ForStatement) || parent.IsKind(SyntaxKind.ForEachStatement) || parent.IsKind(SyntaxKind.ForEachVariableStatement) || parent.IsKind(SyntaxKind.WhileStatement) || parent.IsKind(SyntaxKind.IfStatement) || parent.IsKind(SyntaxKind.LockStatement) || parent.IsKind(SyntaxKind.UsingStatement) || parent.IsKind(SyntaxKind.FixedStatement); case SyntaxKind.ElseKeyword: return token.Parent.IsKind(SyntaxKind.ElseClause); case SyntaxKind.CloseBracketToken: if (token.Parent.IsKind(SyntaxKind.AttributeList)) { // attributes can belong to a statement var container = token.Parent.Parent; if (container is StatementSyntax) { return true; } } return false; } return false; } public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token) { // cases: // } // | // ...; // | // extern alias Goo; // using System; // | // [assembly: Goo] // | if (token.Kind() == SyntaxKind.CloseBraceToken) { var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token && memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } } if (token.Kind() == SyntaxKind.SemicolonToken) { var globalStatement = token.GetAncestor<GlobalStatementSyntax>(); if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token) return true; if (token.Parent is FileScopedNamespaceDeclarationSyntax namespaceDeclaration && namespaceDeclaration.SemicolonToken == token) return true; var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token && memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } var compUnit = token.GetAncestor<CompilationUnitSyntax>(); if (compUnit != null) { if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } } } if (token.Kind() == SyntaxKind.CloseBracketToken) { var compUnit = token.GetAncestor<CompilationUnitSyntax>(); if (compUnit != null) { if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } } } return false; } public static bool IsAfterPossibleCast(this SyntaxToken token) { if (token.Kind() == SyntaxKind.CloseParenToken) { if (token.Parent.IsKind(SyntaxKind.CastExpression)) { return true; } if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var expr = parenExpr.Expression; if (expr is TypeSyntax) { return true; } } } return false; } public static bool IsLastTokenOfQueryClause(this SyntaxToken token) { if (token.IsLastTokenOfNode<QueryClauseSyntax>()) { return true; } if (token.Kind() == SyntaxKind.IdentifierToken && token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword) { return true; } return false; } public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken) { // cases: // #if | // #if goo || | // #if goo && | // #if ( | // #if ! | // Same for elif if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null) { return false; } // #if // #elif if (targetToken.Kind() == SyntaxKind.IfKeyword || targetToken.Kind() == SyntaxKind.ElifKeyword) { return true; } // ( | if (targetToken.Kind() == SyntaxKind.OpenParenToken && targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } // ! | if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix) { return prefix.OperatorToken == targetToken; } // a && // a || if (targetToken.Parent is BinaryExpressionSyntax binary) { return binary.OperatorToken == targetToken; } return false; } public static bool IsOrderByDirectionContext(this SyntaxToken targetToken) { // cases: // orderby a | // orderby a a| // orderby a, b | // orderby a, b a| if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken)) { return false; } var ordering = targetToken.GetAncestor<OrderingSyntax>(); if (ordering == null) { return false; } // orderby a | // orderby a, b | var lastToken = ordering.Expression.GetLastToken(includeSkipped: true); if (targetToken == lastToken) { return true; } return false; } public static bool IsSwitchLabelContext(this SyntaxToken targetToken) { // cases: // case X: | // default: | // switch (e) { | // // case X: Statement(); | if (targetToken.Kind() == SyntaxKind.OpenBraceToken && targetToken.Parent.IsKind(SyntaxKind.SwitchStatement)) { return true; } if (targetToken.Kind() == SyntaxKind.ColonToken) { if (targetToken.Parent.IsKind( SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel)) { return true; } } if (targetToken.Kind() == SyntaxKind.SemicolonToken || targetToken.Kind() == SyntaxKind.CloseBraceToken) { var section = targetToken.GetAncestor<SwitchSectionSyntax>(); if (section != null) { foreach (var statement in section.Statements) { if (targetToken == statement.GetLastToken(includeSkipped: true)) { return true; } } } } return false; } public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken) { return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken) && targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList); } public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken) { // cases: // Goo( | // Goo(expr, | // Goo(bar: | // new Goo( | // new Goo(expr, | // new Goo(bar: | // Goo : base( | // Goo : base(bar: | // Goo : this( | // Goo : this(bar: | // Goo(bar: | if (targetToken.Kind() == SyntaxKind.ColonToken && targetToken.Parent.IsKind(SyntaxKind.NameColon) && targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) && targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList)) { var owner = targetToken.Parent.Parent.Parent.Parent; if (owner.IsKind(SyntaxKind.InvocationExpression) || owner.IsKind(SyntaxKind.ObjectCreationExpression) || owner.IsKind(SyntaxKind.BaseConstructorInitializer) || owner.IsKind(SyntaxKind.ThisConstructorInitializer)) { return true; } } if (targetToken.Kind() == SyntaxKind.OpenParenToken || targetToken.Kind() == SyntaxKind.CommaToken) { if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList)) { if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) || targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) || targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer)) { return true; } // var( | // var(expr, | // Those are more likely to be deconstruction-declarations being typed than invocations a method "var" if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression()) { return true; } } } return false; } public static bool IsUnaryOperatorContext(this SyntaxToken targetToken) { if (targetToken.Kind() == SyntaxKind.OperatorKeyword && targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>()) { return true; } return false; } public static bool IsUnsafeContext(this SyntaxToken targetToken) { return targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) || targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsAfterYieldKeyword(this SyntaxToken targetToken) { // yield | // yield r| return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword); } public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None) { return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) || targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) || targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind); } public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None) where TMemberNode : SyntaxNode { if (!IsAccessorDeclarationContextWorker(ref targetToken)) { return false; } var list = targetToken.GetAncestor<AccessorListSyntax>(); if (list == null) { return false; } // Check if we already have this accessor. (however, don't count it // if the user is *on* that accessor. var existingAccessor = list.Accessors .Select(a => a.Keyword) .FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind)); if (existingAccessor.Kind() != SyntaxKind.None) { var existingAccessorSpan = existingAccessor.Span; if (!existingAccessorSpan.IntersectsWith(position)) { return false; } } var decl = targetToken.GetAncestor<TMemberNode>(); return decl != null; } private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken) { // cases: // int Goo { | // int Goo { private | // int Goo { set { } | // int Goo { set; | // int Goo { [Bar]| // int Goo { readonly | // Consume all preceding access modifiers while (targetToken.Kind() == SyntaxKind.InternalKeyword || targetToken.Kind() == SyntaxKind.PublicKeyword || targetToken.Kind() == SyntaxKind.ProtectedKeyword || targetToken.Kind() == SyntaxKind.PrivateKeyword || targetToken.Kind() == SyntaxKind.ReadOnlyKeyword) { targetToken = targetToken.GetPreviousToken(includeSkipped: true); } // int Goo { | // int Goo { private | if (targetToken.Kind() == SyntaxKind.OpenBraceToken && targetToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } // int Goo { set { } | // int Goo { set { } private | if (targetToken.Kind() == SyntaxKind.CloseBraceToken && targetToken.Parent.IsKind(SyntaxKind.Block) && targetToken.Parent.Parent is AccessorDeclarationSyntax) { return true; } // int Goo { set; | if (targetToken.Kind() == SyntaxKind.SemicolonToken && targetToken.Parent is AccessorDeclarationSyntax) { return true; } // int Goo { [Bar]| if (targetToken.Kind() == SyntaxKind.CloseBracketToken && targetToken.Parent.IsKind(SyntaxKind.AttributeList) && targetToken.Parent.Parent is AccessorDeclarationSyntax) { return true; } return false; } private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node) { if (node.IsKind(SyntaxKind.TypeParameterList)) { if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl)) return typeDecl.TypeParameterList == node; else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl)) return delegateDecl.TypeParameterList == node; } return false; } public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken) { // cases: // interface IGoo<| // interface IGoo<A,| // interface IGoo<[Bar]| // delegate X D<| // delegate X D<A,| // delegate X D<[Bar]| if (targetToken.Kind() == SyntaxKind.LessThanToken && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!)) { return true; } if (targetToken.Kind() == SyntaxKind.CommaToken && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!)) { return true; } if (targetToken.Kind() == SyntaxKind.CloseBracketToken && targetToken.Parent.IsKind(SyntaxKind.AttributeList) && targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent)) { return true; } return false; } public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax) { var argumentList = (BaseArgumentListSyntax)token.Parent; foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { if (item.AsNode() is ArgumentSyntax node && node.NameColon != null) { return true; } } } } return false; } public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!(token.Parent is MemberAccessExpressionSyntax memberAccessExpression)) { return false; } var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken); return typeInfo.Type.IsNumericType(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal static partial class SyntaxTokenExtensions { public static bool IsUsingOrExternKeyword(this SyntaxToken token) { return token.Kind() == SyntaxKind.UsingKeyword || token.Kind() == SyntaxKind.ExternKeyword; } public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token) { if (token.IsKind(SyntaxKind.UsingKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.UsingKeyword == token) { return true; } } return false; } public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token) { if (token.IsKind(SyntaxKind.StaticKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.StaticKeyword == token) { return true; } } return false; } public static bool IsBeginningOfStatementContext(this SyntaxToken token) { // cases: // { // | // } // | // Note, the following is *not* a legal statement context: // do { } | // ...; // | // case 0: // | // default: // | // label: // | // if (goo) // | // while (true) // | // do // | // for (;;) // | // foreach (var v in c) // | // else // | // using (expr) // | // fixed (void* v = &expr) // | // lock (expr) // | // for ( ; ; Goo(), | // After attribute lists on a statement: // [Bar] // | switch (token.Kind()) { case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block): return true; case SyntaxKind.SemicolonToken: var statement = token.GetAncestor<StatementSyntax>(); return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) && statement.GetLastToken(includeZeroWidth: true) == token; case SyntaxKind.CloseBraceToken: if (token.Parent.IsKind(SyntaxKind.Block)) { if (token.Parent.Parent is StatementSyntax) { // Most blocks that are the child of statement are places // that we can follow with another statement. i.e.: // if { } // while () { } // There are two exceptions. // try {} // do {} if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) && !token.Parent.IsParentKind(SyntaxKind.DoStatement)) { return true; } } else if ( token.Parent.IsParentKind(SyntaxKind.ElseClause) || token.Parent.IsParentKind(SyntaxKind.FinallyClause) || token.Parent.IsParentKind(SyntaxKind.CatchClause) || token.Parent.IsParentKind(SyntaxKind.SwitchSection)) { return true; } } if (token.Parent.IsKind(SyntaxKind.SwitchStatement)) { return true; } return false; case SyntaxKind.ColonToken: return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel, SyntaxKind.LabeledStatement); case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement): return true; case SyntaxKind.CloseParenToken: var parent = token.Parent; return parent.IsKind(SyntaxKind.ForStatement) || parent.IsKind(SyntaxKind.ForEachStatement) || parent.IsKind(SyntaxKind.ForEachVariableStatement) || parent.IsKind(SyntaxKind.WhileStatement) || parent.IsKind(SyntaxKind.IfStatement) || parent.IsKind(SyntaxKind.LockStatement) || parent.IsKind(SyntaxKind.UsingStatement) || parent.IsKind(SyntaxKind.FixedStatement); case SyntaxKind.ElseKeyword: return token.Parent.IsKind(SyntaxKind.ElseClause); case SyntaxKind.CloseBracketToken: if (token.Parent.IsKind(SyntaxKind.AttributeList)) { // attributes can belong to a statement var container = token.Parent.Parent; if (container is StatementSyntax) { return true; } } return false; } return false; } public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token) { // cases: // } // | // ...; // | // extern alias Goo; // using System; // | // [assembly: Goo] // | if (token.Kind() == SyntaxKind.CloseBraceToken) { var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token && memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } } if (token.Kind() == SyntaxKind.SemicolonToken) { var globalStatement = token.GetAncestor<GlobalStatementSyntax>(); if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token) return true; if (token.Parent is FileScopedNamespaceDeclarationSyntax namespaceDeclaration && namespaceDeclaration.SemicolonToken == token) return true; var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token && memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } var compUnit = token.GetAncestor<CompilationUnitSyntax>(); if (compUnit != null) { if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } } } if (token.Kind() == SyntaxKind.CloseBracketToken) { var compUnit = token.GetAncestor<CompilationUnitSyntax>(); if (compUnit != null) { if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token) { return true; } } } return false; } public static bool IsAfterPossibleCast(this SyntaxToken token) { if (token.Kind() == SyntaxKind.CloseParenToken) { if (token.Parent.IsKind(SyntaxKind.CastExpression)) { return true; } if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var expr = parenExpr.Expression; if (expr is TypeSyntax) { return true; } } } return false; } public static bool IsLastTokenOfQueryClause(this SyntaxToken token) { if (token.IsLastTokenOfNode<QueryClauseSyntax>()) { return true; } if (token.Kind() == SyntaxKind.IdentifierToken && token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword) { return true; } return false; } public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken) { // cases: // #if | // #if goo || | // #if goo && | // #if ( | // #if ! | // Same for elif if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null) { return false; } // #if // #elif if (targetToken.Kind() == SyntaxKind.IfKeyword || targetToken.Kind() == SyntaxKind.ElifKeyword) { return true; } // ( | if (targetToken.Kind() == SyntaxKind.OpenParenToken && targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } // ! | if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix) { return prefix.OperatorToken == targetToken; } // a && // a || if (targetToken.Parent is BinaryExpressionSyntax binary) { return binary.OperatorToken == targetToken; } return false; } public static bool IsOrderByDirectionContext(this SyntaxToken targetToken) { // cases: // orderby a | // orderby a a| // orderby a, b | // orderby a, b a| if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken)) { return false; } var ordering = targetToken.GetAncestor<OrderingSyntax>(); if (ordering == null) { return false; } // orderby a | // orderby a, b | var lastToken = ordering.Expression.GetLastToken(includeSkipped: true); if (targetToken == lastToken) { return true; } return false; } public static bool IsSwitchLabelContext(this SyntaxToken targetToken) { // cases: // case X: | // default: | // switch (e) { | // // case X: Statement(); | if (targetToken.Kind() == SyntaxKind.OpenBraceToken && targetToken.Parent.IsKind(SyntaxKind.SwitchStatement)) { return true; } if (targetToken.Kind() == SyntaxKind.ColonToken) { if (targetToken.Parent.IsKind( SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel)) { return true; } } if (targetToken.Kind() == SyntaxKind.SemicolonToken || targetToken.Kind() == SyntaxKind.CloseBraceToken) { var section = targetToken.GetAncestor<SwitchSectionSyntax>(); if (section != null) { foreach (var statement in section.Statements) { if (targetToken == statement.GetLastToken(includeSkipped: true)) { return true; } } } } return false; } public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken) { return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken) && targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList); } public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken) { // cases: // Goo( | // Goo(expr, | // Goo(bar: | // new Goo( | // new Goo(expr, | // new Goo(bar: | // Goo : base( | // Goo : base(bar: | // Goo : this( | // Goo : this(bar: | // Goo(bar: | if (targetToken.Kind() == SyntaxKind.ColonToken && targetToken.Parent.IsKind(SyntaxKind.NameColon) && targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) && targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList)) { var owner = targetToken.Parent.Parent.Parent.Parent; if (owner.IsKind(SyntaxKind.InvocationExpression) || owner.IsKind(SyntaxKind.ObjectCreationExpression) || owner.IsKind(SyntaxKind.BaseConstructorInitializer) || owner.IsKind(SyntaxKind.ThisConstructorInitializer)) { return true; } } if (targetToken.Kind() == SyntaxKind.OpenParenToken || targetToken.Kind() == SyntaxKind.CommaToken) { if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList)) { if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) || targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) || targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer)) { return true; } // var( | // var(expr, | // Those are more likely to be deconstruction-declarations being typed than invocations a method "var" if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression()) { return true; } } } return false; } public static bool IsUnaryOperatorContext(this SyntaxToken targetToken) { if (targetToken.Kind() == SyntaxKind.OperatorKeyword && targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>()) { return true; } return false; } public static bool IsUnsafeContext(this SyntaxToken targetToken) { return targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) || targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsAfterYieldKeyword(this SyntaxToken targetToken) { // yield | // yield r| return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword); } public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None) { return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) || targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) || targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind); } public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None) where TMemberNode : SyntaxNode { if (!IsAccessorDeclarationContextWorker(ref targetToken)) { return false; } var list = targetToken.GetAncestor<AccessorListSyntax>(); if (list == null) { return false; } // Check if we already have this accessor. (however, don't count it // if the user is *on* that accessor. var existingAccessor = list.Accessors .Select(a => a.Keyword) .FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind)); if (existingAccessor.Kind() != SyntaxKind.None) { var existingAccessorSpan = existingAccessor.Span; if (!existingAccessorSpan.IntersectsWith(position)) { return false; } } var decl = targetToken.GetAncestor<TMemberNode>(); return decl != null; } private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken) { // cases: // int Goo { | // int Goo { private | // int Goo { set { } | // int Goo { set; | // int Goo { [Bar]| // int Goo { readonly | // Consume all preceding access modifiers while (targetToken.Kind() == SyntaxKind.InternalKeyword || targetToken.Kind() == SyntaxKind.PublicKeyword || targetToken.Kind() == SyntaxKind.ProtectedKeyword || targetToken.Kind() == SyntaxKind.PrivateKeyword || targetToken.Kind() == SyntaxKind.ReadOnlyKeyword) { targetToken = targetToken.GetPreviousToken(includeSkipped: true); } // int Goo { | // int Goo { private | if (targetToken.Kind() == SyntaxKind.OpenBraceToken && targetToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } // int Goo { set { } | // int Goo { set { } private | if (targetToken.Kind() == SyntaxKind.CloseBraceToken && targetToken.Parent.IsKind(SyntaxKind.Block) && targetToken.Parent.Parent is AccessorDeclarationSyntax) { return true; } // int Goo { set; | if (targetToken.Kind() == SyntaxKind.SemicolonToken && targetToken.Parent is AccessorDeclarationSyntax) { return true; } // int Goo { [Bar]| if (targetToken.Kind() == SyntaxKind.CloseBracketToken && targetToken.Parent.IsKind(SyntaxKind.AttributeList) && targetToken.Parent.Parent is AccessorDeclarationSyntax) { return true; } return false; } private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node) { if (node.IsKind(SyntaxKind.TypeParameterList)) { if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl)) return typeDecl.TypeParameterList == node; else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl)) return delegateDecl.TypeParameterList == node; } return false; } public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken) { // cases: // interface IGoo<| // interface IGoo<A,| // interface IGoo<[Bar]| // delegate X D<| // delegate X D<A,| // delegate X D<[Bar]| if (targetToken.Kind() == SyntaxKind.LessThanToken && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!)) { return true; } if (targetToken.Kind() == SyntaxKind.CommaToken && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!)) { return true; } if (targetToken.Kind() == SyntaxKind.CloseBracketToken && targetToken.Parent.IsKind(SyntaxKind.AttributeList) && targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) && IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent)) { return true; } return false; } public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax) { var argumentList = (BaseArgumentListSyntax)token.Parent; foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { if (item.AsNode() is ArgumentSyntax node && node.NameColon != null) { return true; } } } } return false; } public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!(token.Parent is MemberAccessExpressionSyntax memberAccessExpression)) { return false; } var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken); return typeInfo.Type.IsNumericType(); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; [assembly: DebuggerTypeProxy(typeof(MefLanguageServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<ILanguageService, WorkspaceServiceMetadata>>))] namespace Microsoft.CodeAnalysis.Host.Mef { internal sealed class MefLanguageServices : HostLanguageServices { private readonly MefWorkspaceServices _workspaceServices; private readonly string _language; private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; private ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>> _serviceMap = ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>>.Empty; public MefLanguageServices( MefWorkspaceServices workspaceServices, string language) { _workspaceServices = workspaceServices; _language = language; var hostServices = workspaceServices.HostExportProvider; var services = hostServices.GetExports<ILanguageService, LanguageServiceMetadata>(); var factories = hostServices.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>() .Select(lz => new Lazy<ILanguageService, LanguageServiceMetadata>(() => lz.Value.CreateLanguageService(this), lz.Metadata)); _services = services.Concat(factories).Where(lz => lz.Metadata.Language == language).ToImmutableArray(); } public override HostWorkspaceServices WorkspaceServices => _workspaceServices; public override string Language => _language; public bool HasServices { get { return _services.Length > 0; } } public override TLanguageService GetService<TLanguageService>() { if (TryGetService(typeof(TLanguageService), out var service)) { return (TLanguageService)service.Value; } else { return default; } } internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, LanguageServiceMetadata> service) { if (!_serviceMap.TryGetValue(serviceType, out service)) { service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype => { // PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations. var assemblyQualifiedName = svctype.AssemblyQualifiedName; return PickLanguageService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName)); }); } return service != null; } private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services) { Lazy<ILanguageService, LanguageServiceMetadata> service; #if !CODE_STYLE // test layer overrides everything else if (TryGetServiceByLayer(ServiceLayer.Test, services, out service)) { return service; } #endif // workspace specific kind is best if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out service)) { return service; } // host layer overrides editor, desktop or default if (TryGetServiceByLayer(ServiceLayer.Host, services, out service)) { return service; } // editor layer overrides desktop or default if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service)) { return service; } // desktop layer overrides default if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service)) { return service; } // that just leaves default if (TryGetServiceByLayer(ServiceLayer.Default, services, out service)) { return service; } // no service return null; } private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services, out Lazy<ILanguageService, LanguageServiceMetadata> service) { service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer); return service != null; } internal sealed class LazyServiceMetadataDebuggerProxy { private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> services) => _services = services; public (string type, string layer)[] Metadata => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; [assembly: DebuggerTypeProxy(typeof(MefLanguageServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<ILanguageService, WorkspaceServiceMetadata>>))] namespace Microsoft.CodeAnalysis.Host.Mef { internal sealed class MefLanguageServices : HostLanguageServices { private readonly MefWorkspaceServices _workspaceServices; private readonly string _language; private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; private ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>> _serviceMap = ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>>.Empty; public MefLanguageServices( MefWorkspaceServices workspaceServices, string language) { _workspaceServices = workspaceServices; _language = language; var hostServices = workspaceServices.HostExportProvider; var services = hostServices.GetExports<ILanguageService, LanguageServiceMetadata>(); var factories = hostServices.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>() .Select(lz => new Lazy<ILanguageService, LanguageServiceMetadata>(() => lz.Value.CreateLanguageService(this), lz.Metadata)); _services = services.Concat(factories).Where(lz => lz.Metadata.Language == language).ToImmutableArray(); } public override HostWorkspaceServices WorkspaceServices => _workspaceServices; public override string Language => _language; public bool HasServices { get { return _services.Length > 0; } } public override TLanguageService GetService<TLanguageService>() { if (TryGetService(typeof(TLanguageService), out var service)) { return (TLanguageService)service.Value; } else { return default; } } internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, LanguageServiceMetadata> service) { if (!_serviceMap.TryGetValue(serviceType, out service)) { service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype => { // PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations. var assemblyQualifiedName = svctype.AssemblyQualifiedName; return PickLanguageService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName)); }); } return service != null; } private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services) { Lazy<ILanguageService, LanguageServiceMetadata> service; #if !CODE_STYLE // test layer overrides everything else if (TryGetServiceByLayer(ServiceLayer.Test, services, out service)) { return service; } #endif // workspace specific kind is best if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out service)) { return service; } // host layer overrides editor, desktop or default if (TryGetServiceByLayer(ServiceLayer.Host, services, out service)) { return service; } // editor layer overrides desktop or default if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service)) { return service; } // desktop layer overrides default if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service)) { return service; } // that just leaves default if (TryGetServiceByLayer(ServiceLayer.Default, services, out service)) { return service; } // no service return null; } private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services, out Lazy<ILanguageService, LanguageServiceMetadata> service) { service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer); return service != null; } internal sealed class LazyServiceMetadataDebuggerProxy { private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> services) => _services = services; public (string type, string layer)[] Metadata => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/LoadingIndexers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { // CONSIDER: it might be worthwhile to promote some of these sample types to a test resource DLL public class LoadingIndexers : CSharpTestBase { [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadReadWriteIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_Item(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadWriteOnlyIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance void set_Item(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, false, true, "System.Int32 C.this[System.Int32 x] { set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadReadOnlyIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, true, false, "System.Int32 C.this[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadIndexerWithAlternateName() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('NotItem')} .method public hidebysig specialname instance int32 get_NotItem(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_NotItem(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 NotItem(int32) { .get instance int32 C::get_NotItem(int32) .set instance void C::set_NotItem(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("NotItem", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadIndexerWithAccessorAsDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_NotItem')} .method public hidebysig specialname instance int32 get_NotItem(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_NotItem(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 NotItem(int32) { .get instance int32 C::get_NotItem(int32) .set instance void C::set_NotItem(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("get_NotItem", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadComplexIndexers() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Accessor1')} .method public hidebysig specialname instance int32 Accessor1(int32 x, int64 y) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void Accessor2(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname instance void Accessor3(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Indexer1(int32, int64) { .get instance int32 C::Accessor1(int32, int64) .set instance void C::Accessor2(int32, int64, int32) } .property instance int32 Indexer2(int32, int64) { .get instance int32 C::Accessor1(int32, int64) .set instance void C::Accessor3(int32, int64, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Accessor1", @class.DefaultMemberName); var indexer1 = @class.GetIndexer<PEPropertySymbol>("Indexer1"); CheckIndexer(indexer1, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true); var indexer2 = @class.GetIndexer<PEPropertySymbol>("Indexer2"); CheckIndexer(indexer2, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true); }); } [ClrOnlyFact] public void LoadNonIndexer_NoDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("", @class.DefaultMemberName); //placeholder value to avoid refetching var property = @class.GetMember<PEPropertySymbol>("Item"); CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadNonIndexer_NotDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('NotItem')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("NotItem", @class.DefaultMemberName); var property = @class.GetMember<PEPropertySymbol>("Item"); CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadNonGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit NonGeneric extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance int32 get_Item(int64 x) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(int64 x, int32 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static int32 get_Item(int64 x) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(int64 x, int32 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance int32 Instance(int64) { .get instance int32 NonGeneric::get_Item(int64) .set instance void NonGeneric::set_Item(int64, int32) } .property int32 Static(int64) { .get int32 NonGeneric::get_Item(int64) .set void NonGeneric::set_Item(int64, int32) } } // end of class NonGeneric "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "NonGeneric", "System.Int32 NonGeneric.this[System.Int64 x] { get; set; }")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit Generic`2<T,U> extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance !T get_Item(!U u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(!U u, !T 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static !T get_Item(!U u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(!U u, !T 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance !T Instance(!U) { .get instance !T Generic`2::get_Item(!U) .set instance void Generic`2::set_Item(!U, !T) } .property !T Static(!U) { .get !T Generic`2::get_Item(!U) .set void Generic`2::set_Item(!U, !T) } } // end of class Generic`2 "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "Generic", "T Generic<T, U>.this[U u] { get; set; }")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadClosedGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit ClosedGeneric extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance class [mscorlib]System.Collections.Generic.List`1<int32> get_Item(class [mscorlib]System.Action`1<int16> u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(class [mscorlib]System.Action`1<int16> u, class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static class [mscorlib]System.Collections.Generic.List`1<int32> get_Item(class [mscorlib]System.Action`1<int16> u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(class [mscorlib]System.Action`1<int16> u, class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance class [mscorlib]System.Collections.Generic.List`1<int32> Instance(class [mscorlib]System.Action`1<int16>) { .get instance class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>) .set instance void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>, class [mscorlib]System.Collections.Generic.List`1<int32>) } .property class [mscorlib]System.Collections.Generic.List`1<int32> Static(class [mscorlib]System.Action`1<int16>) { .get class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>) .set void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>, class [mscorlib]System.Collections.Generic.List`1<int32>) } } // end of class ClosedGeneric "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "ClosedGeneric", "System.Collections.Generic.List<System.Int32> ClosedGeneric.this[System.Action<System.Int16> u] { get; set; }")); } [Fact] public void LoadIndexerWithRefParam() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Indexers); var @class = assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("RefIndexer"); var indexer = (PropertySymbol)@class.GetMembers().Where(m => m.Kind == SymbolKind.Property).Single(); Assert.Equal(RefKind.Ref, indexer.Parameters.Single().RefKind); Assert.True(indexer.MustCallMethodsDirectly); } private static void CheckInstanceAndStaticIndexers(CSharpCompilation compilation, string className, string indexerDisplayString) { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>(className); var instanceIndexer = @class.GetIndexer<PEPropertySymbol>("Instance"); Assert.False(instanceIndexer.IsStatic); CheckIndexer(instanceIndexer, true, true, indexerDisplayString); var staticIndexer = @class.GetIndexer<PEPropertySymbol>("Static"); //not allowed in C# Assert.True(staticIndexer.IsStatic); CheckIndexer(staticIndexer, true, true, indexerDisplayString); } /// <summary> /// The accessor and the property have signatures. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadAccessorPropertySignatureMismatch() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig specialname instance int32 get_Item(string s) cil managed { ldc.i4.0 ret } .property instance int32 ParameterCount(string, char) { .get instance int32 C::get_Item(string) } .method public hidebysig specialname instance int32 get_Item(string s, string c) cil managed { ldc.i4.0 ret } .property instance int32 ParameterTypes(string, char) { .get instance int32 C::get_Item(string, string) } .method public hidebysig specialname instance int32 get_Item(string s, char modopt(int32) c) cil managed { ldc.i4.0 ret } .property instance int32 ReturnType(string, char) { .get instance char C::get_Item(string, string) } .property instance int32 ParameterModopt(string, char) { .get instance int32 C::get_Item(string, char modopt(int32)) } .method public hidebysig specialname instance char get_Item(string s, string c) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance int32 modopt(int32) get_Item(string s, char c) cil managed { ldc.i4.0 ret } .property instance int32 ReturnTypeModopt(string, char) { .get instance int32 modopt(int32) C::get_Item(string, char) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var parameterCountIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterCount"); Assert.True(parameterCountIndexer.IsIndexer); Assert.True(parameterCountIndexer.MustCallMethodsDirectly); Assert.NotEqual(parameterCountIndexer.ParameterCount, parameterCountIndexer.GetMethod.ParameterCount); var parameterTypesIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterTypes"); Assert.True(parameterTypesIndexer.IsIndexer); Assert.True(parameterTypesIndexer.MustCallMethodsDirectly); Assert.NotEqual(parameterTypesIndexer.Parameters.Last().Type, parameterTypesIndexer.GetMethod.Parameters.Last().Type); var returnTypeIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnType"); Assert.True(returnTypeIndexer.IsIndexer); Assert.True(returnTypeIndexer.MustCallMethodsDirectly); Assert.NotEqual(returnTypeIndexer.Type, returnTypeIndexer.GetMethod.ReturnType); var parameterModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterModopt"); Assert.True(parameterModoptIndexer.IsIndexer); Assert.False(parameterModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in parameter type) Assert.NotEqual(parameterModoptIndexer.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length, parameterModoptIndexer.GetMethod.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length); var returnTypeModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnTypeModopt"); Assert.True(returnTypeModoptIndexer.IsIndexer); Assert.False(returnTypeModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in return type) Assert.NotEqual(returnTypeModoptIndexer.TypeWithAnnotations.CustomModifiers.Length, returnTypeModoptIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Length); }); } [ClrOnlyFact] public void LoadParameterNames() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } // NB: getter and setter have different parameter names .method public hidebysig specialname instance void set_Item(int32 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 ReadWrite(int32) { .get instance int32 C::get_Item(int32) .set instance void C::set_Item(int32, int32) } .property instance int32 ReadOnly(int32) { .get instance int32 C::get_Item(int32) } .property instance int32 WriteOnly(int32) { .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var property1 = @class.GetMember<PEPropertySymbol>("ReadWrite"); var property1ParamName = property1.Parameters.Single().Name; // NOTE: prefer setter Assert.NotEqual(property1ParamName, property1.GetMethod.Parameters.Single().Name); Assert.Equal(property1ParamName, property1.SetMethod.Parameters.First().Name); var property2 = @class.GetMember<PEPropertySymbol>("ReadOnly"); var property2ParamName = property2.Parameters.Single().Name; Assert.Equal(property2ParamName, property2.GetMethod.Parameters.Single().Name); var property3 = @class.GetMember<PEPropertySymbol>("WriteOnly"); var property3ParamName = property3.Parameters.Single().Name; Assert.Equal(property3ParamName, property3.SetMethod.Parameters.First().Name); }); } /// <remarks> /// Only testing parameter count mismatch. There isn't specific handling for other /// types of bogus properties - just setter param name if setter available and getter /// param name if getter available (i.e. same as success case). /// </remarks> [ClrOnlyFact] public void LoadBogusParameterNames() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x, int32 y) cil managed { ldc.i4.0 ret } // accessor has too many parameters .property instance int32 TooMany(int32) { .get instance int32 C::get_Item(int32, int32) } // accessor has too few parameters .property instance int32 TooFew(int32, int32, int32) { .get instance int32 C::get_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var accessor = @class.GetMember<MethodSymbol>("get_Item"); var accessParam0Name = accessor.Parameters[0].Name; var accessParam1Name = accessor.Parameters[1].Name; var property1 = @class.GetMember<PEPropertySymbol>("TooMany"); Assert.Equal(accessParam0Name, property1.Parameters[0].Name); var property2 = @class.GetMember<PEPropertySymbol>("TooFew"); var property2Params = property2.Parameters; Assert.Equal(accessParam0Name, property2Params[0].Name); Assert.Equal(accessParam1Name, property2Params[1].Name); Assert.Equal("value", property2Params[2].Name); //filler name }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadParamArrayAttribute() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('accessor')} .method public hidebysig specialname instance int32 accessor(int32[] a) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ldc.i4.0 ret } .method public hidebysig specialname instance void accessor(int32[] a, int32 'value') cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 ReadWrite(int32[]) { .get instance int32 C::accessor(int32[]) .set instance void C::accessor(int32[], int32) } .property instance int32 ReadOnly(int32[]) { .get instance int32 C::accessor(int32[]) } .property instance int32 WriteOnly(int32[]) { .set instance void C::accessor(int32[], int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var readWrite = @class.GetIndexer<PEPropertySymbol>("ReadWrite"); Assert.True(readWrite.IsIndexer); Assert.False(readWrite.MustCallMethodsDirectly); Assert.True(readWrite.Parameters.Last().IsParams); var readOnly = @class.GetIndexer<PEPropertySymbol>("ReadOnly"); Assert.True(readOnly.IsIndexer); Assert.False(readOnly.MustCallMethodsDirectly); Assert.True(readOnly.Parameters.Last().IsParams); var writeOnly = @class.GetIndexer<PEPropertySymbol>("WriteOnly"); Assert.True(writeOnly.IsIndexer); Assert.False(writeOnly.MustCallMethodsDirectly); Assert.True(writeOnly.Parameters.Last().IsParams); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadBogusParamArrayAttribute() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('params')} .method public hidebysig specialname instance int32 params(int32[] a) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ldc.i4.0 ret } .method public hidebysig specialname instance int32 noParams(int32[] a) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void params(int32[] a, int32 'value') cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } .method public hidebysig specialname instance void noParams(int32[] a, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 OnlyGetter(int32[]) { .get instance int32 C::params(int32[]) .set instance void C::noParams(int32[], int32) } .property instance int32 OnlySetter(int32[]) { .get instance int32 C::noParams(int32[]) .set instance void C::params(int32[], int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var readWrite = @class.GetIndexer<PEPropertySymbol>("OnlyGetter"); Assert.True(readWrite.IsIndexer); Assert.True(readWrite.MustCallMethodsDirectly); Assert.False(readWrite.Parameters.Last().IsParams); //favour setter var readOnly = @class.GetIndexer<PEPropertySymbol>("OnlySetter"); Assert.True(readWrite.IsIndexer); Assert.True(readOnly.MustCallMethodsDirectly); Assert.True(readOnly.Parameters.Last().IsParams); //favour setter }); } private static void CheckIndexer(PropertySymbol indexer, bool expectGetter, bool expectSetter, string indexerDisplayString, bool suppressAssociatedPropertyCheck = false) { CheckParameterizedProperty(indexer, expectGetter, expectSetter, indexerDisplayString, true, suppressAssociatedPropertyCheck); } private static void CheckNonIndexer(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString) { CheckParameterizedProperty(property, expectGetter, expectSetter, propertyDisplayString, false, true); } private static void CheckParameterizedProperty(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString, bool expectIndexer, bool suppressAssociatedPropertyCheck) { Assert.Equal(SymbolKind.Property, property.Kind); Assert.Equal(expectIndexer, property.IsIndexer); Assert.NotEqual(expectIndexer, property.MustCallMethodsDirectly); Assert.Equal(propertyDisplayString, property.ToTestDisplayString()); if (expectGetter) { CheckAccessorShape(property.GetMethod, true, property, expectIndexer, suppressAssociatedPropertyCheck); } else { Assert.Null(property.GetMethod); } if (expectSetter) { CheckAccessorShape(property.SetMethod, false, property, expectIndexer, suppressAssociatedPropertyCheck); } else { Assert.Null(property.SetMethod); } } private static void CheckAccessorShape(MethodSymbol accessor, bool accessorIsGetMethod, PropertySymbol property, bool propertyIsIndexer, bool suppressAssociatedPropertyCheck) { Assert.NotNull(accessor); if (propertyIsIndexer) { if (!suppressAssociatedPropertyCheck) { Assert.Same(property, accessor.AssociatedSymbol); } } else { Assert.Null(accessor.AssociatedSymbol); Assert.Equal(MethodKind.Ordinary, accessor.MethodKind); } if (accessorIsGetMethod) { Assert.Equal(propertyIsIndexer ? MethodKind.PropertyGet : MethodKind.Ordinary, accessor.MethodKind); Assert.Equal(property.Type, accessor.ReturnType); Assert.Equal(property.ParameterCount, accessor.ParameterCount); } else { Assert.Equal(propertyIsIndexer ? MethodKind.PropertySet : MethodKind.Ordinary, accessor.MethodKind); Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); Assert.Equal(property.Type, accessor.Parameters.Last().Type); Assert.Equal(property.ParameterCount + 1, accessor.ParameterCount); } // NOTE: won't check last param of setter - that was handled above. for (int i = 0; i < property.ParameterCount; i++) { Assert.Equal(property.Parameters[i].Type, accessor.Parameters[i].Type); } Assert.Equal(property.IsAbstract, accessor.IsAbstract); Assert.Equal(property.IsOverride, @accessor.IsOverride); Assert.Equal(property.IsVirtual, @accessor.IsVirtual); Assert.Equal(property.IsSealed, @accessor.IsSealed); Assert.Equal(property.IsExtern, @accessor.IsExtern); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadExplicitImplementation() { string ilSource = @" .class interface public abstract auto ansi I { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32 x) cil managed { } // end of method I::get_Item .method public hidebysig newslot specialname abstract virtual instance void set_Item(int32 x, int32 'value') cil managed { } // end of method I::set_Item .property instance int32 Item(int32) { .get instance int32 I::get_Item(int32) .set instance void I::set_Item(int32, int32) } // end of property I::Item } // end of class I .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements I { .method private hidebysig newslot specialname virtual final instance int32 I.get_Item(int32 x) cil managed { .override I::get_Item ldnull throw } .method private hidebysig newslot specialname virtual final instance void I.set_Item(int32 x, int32 'value') cil managed { .override I::set_Item ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 I.Item(int32) { .get instance int32 C::I.get_Item(int32) .set instance void C::I.set_Item(int32, int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @interface = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("I"); var interfaceIndexer = @interface.Indexers.Single(); Assert.True(interfaceIndexer.IsIndexer); var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var classIndexer = (PropertySymbol)@class.GetMembers().Single(s => s.Kind == SymbolKind.Property); Assert.False(classIndexer.IsIndexer); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexer)); Assert.Equal(interfaceIndexer, classIndexer.ExplicitInterfaceImplementations.Single()); }); } [Fact] public void LoadImplicitImplementation() { } [Fact] public void LoadOverriding() { } [Fact] public void LoadHiding() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { // CONSIDER: it might be worthwhile to promote some of these sample types to a test resource DLL public class LoadingIndexers : CSharpTestBase { [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadReadWriteIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_Item(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadWriteOnlyIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance void set_Item(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, false, true, "System.Int32 C.this[System.Int32 x] { set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadReadOnlyIndexer() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Item", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("Item"); CheckIndexer(indexer, true, false, "System.Int32 C.this[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadIndexerWithAlternateName() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('NotItem')} .method public hidebysig specialname instance int32 get_NotItem(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_NotItem(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 NotItem(int32) { .get instance int32 C::get_NotItem(int32) .set instance void C::set_NotItem(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("NotItem", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadIndexerWithAccessorAsDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_NotItem')} .method public hidebysig specialname instance int32 get_NotItem(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void set_NotItem(int32 x, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 NotItem(int32) { .get instance int32 C::get_NotItem(int32) .set instance void C::set_NotItem(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("get_NotItem", @class.DefaultMemberName); var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem"); CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadComplexIndexers() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Accessor1')} .method public hidebysig specialname instance int32 Accessor1(int32 x, int64 y) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void Accessor2(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname instance void Accessor3(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Indexer1(int32, int64) { .get instance int32 C::Accessor1(int32, int64) .set instance void C::Accessor2(int32, int64, int32) } .property instance int32 Indexer2(int32, int64) { .get instance int32 C::Accessor1(int32, int64) .set instance void C::Accessor3(int32, int64, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("Accessor1", @class.DefaultMemberName); var indexer1 = @class.GetIndexer<PEPropertySymbol>("Indexer1"); CheckIndexer(indexer1, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true); var indexer2 = @class.GetIndexer<PEPropertySymbol>("Indexer2"); CheckIndexer(indexer2, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true); }); } [ClrOnlyFact] public void LoadNonIndexer_NoDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("", @class.DefaultMemberName); //placeholder value to avoid refetching var property = @class.GetMember<PEPropertySymbol>("Item"); CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadNonIndexer_NotDefaultMember() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('NotItem')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 C::get_Item(int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); Assert.Equal("NotItem", @class.DefaultMemberName); var property = @class.GetMember<PEPropertySymbol>("Item"); CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }"); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadNonGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit NonGeneric extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance int32 get_Item(int64 x) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(int64 x, int32 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static int32 get_Item(int64 x) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(int64 x, int32 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance int32 Instance(int64) { .get instance int32 NonGeneric::get_Item(int64) .set instance void NonGeneric::set_Item(int64, int32) } .property int32 Static(int64) { .get int32 NonGeneric::get_Item(int64) .set void NonGeneric::set_Item(int64, int32) } } // end of class NonGeneric "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "NonGeneric", "System.Int32 NonGeneric.this[System.Int64 x] { get; set; }")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit Generic`2<T,U> extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance !T get_Item(!U u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(!U u, !T 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static !T get_Item(!U u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(!U u, !T 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance !T Instance(!U) { .get instance !T Generic`2::get_Item(!U) .set instance void Generic`2::set_Item(!U, !T) } .property !T Static(!U) { .get !T Generic`2::get_Item(!U) .set void Generic`2::set_Item(!U, !T) } } // end of class Generic`2 "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "Generic", "T Generic<T, U>.this[U u] { get; set; }")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadClosedGenericIndexers() { string ilSource = @" .class public auto ansi beforefieldinit ClosedGeneric extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname virtual instance class [mscorlib]System.Collections.Generic.List`1<int32> get_Item(class [mscorlib]System.Action`1<int16> u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual instance void set_Item(class [mscorlib]System.Action`1<int16> u, class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static class [mscorlib]System.Collections.Generic.List`1<int32> get_Item(class [mscorlib]System.Action`1<int16> u) cil managed { ldnull throw } .method public hidebysig newslot specialname virtual static void set_Item(class [mscorlib]System.Action`1<int16> u, class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldnull throw } .property instance class [mscorlib]System.Collections.Generic.List`1<int32> Instance(class [mscorlib]System.Action`1<int16>) { .get instance class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>) .set instance void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>, class [mscorlib]System.Collections.Generic.List`1<int32>) } .property class [mscorlib]System.Collections.Generic.List`1<int32> Static(class [mscorlib]System.Action`1<int16>) { .get class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>) .set void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>, class [mscorlib]System.Collections.Generic.List`1<int32>) } } // end of class ClosedGeneric "; CompileWithCustomILSource("", ilSource, compilation => CheckInstanceAndStaticIndexers(compilation, "ClosedGeneric", "System.Collections.Generic.List<System.Int32> ClosedGeneric.this[System.Action<System.Int16> u] { get; set; }")); } [Fact] public void LoadIndexerWithRefParam() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Indexers); var @class = assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("RefIndexer"); var indexer = (PropertySymbol)@class.GetMembers().Where(m => m.Kind == SymbolKind.Property).Single(); Assert.Equal(RefKind.Ref, indexer.Parameters.Single().RefKind); Assert.True(indexer.MustCallMethodsDirectly); } private static void CheckInstanceAndStaticIndexers(CSharpCompilation compilation, string className, string indexerDisplayString) { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>(className); var instanceIndexer = @class.GetIndexer<PEPropertySymbol>("Instance"); Assert.False(instanceIndexer.IsStatic); CheckIndexer(instanceIndexer, true, true, indexerDisplayString); var staticIndexer = @class.GetIndexer<PEPropertySymbol>("Static"); //not allowed in C# Assert.True(staticIndexer.IsStatic); CheckIndexer(staticIndexer, true, true, indexerDisplayString); } /// <summary> /// The accessor and the property have signatures. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadAccessorPropertySignatureMismatch() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig specialname instance int32 get_Item(string s) cil managed { ldc.i4.0 ret } .property instance int32 ParameterCount(string, char) { .get instance int32 C::get_Item(string) } .method public hidebysig specialname instance int32 get_Item(string s, string c) cil managed { ldc.i4.0 ret } .property instance int32 ParameterTypes(string, char) { .get instance int32 C::get_Item(string, string) } .method public hidebysig specialname instance int32 get_Item(string s, char modopt(int32) c) cil managed { ldc.i4.0 ret } .property instance int32 ReturnType(string, char) { .get instance char C::get_Item(string, string) } .property instance int32 ParameterModopt(string, char) { .get instance int32 C::get_Item(string, char modopt(int32)) } .method public hidebysig specialname instance char get_Item(string s, string c) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance int32 modopt(int32) get_Item(string s, char c) cil managed { ldc.i4.0 ret } .property instance int32 ReturnTypeModopt(string, char) { .get instance int32 modopt(int32) C::get_Item(string, char) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var parameterCountIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterCount"); Assert.True(parameterCountIndexer.IsIndexer); Assert.True(parameterCountIndexer.MustCallMethodsDirectly); Assert.NotEqual(parameterCountIndexer.ParameterCount, parameterCountIndexer.GetMethod.ParameterCount); var parameterTypesIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterTypes"); Assert.True(parameterTypesIndexer.IsIndexer); Assert.True(parameterTypesIndexer.MustCallMethodsDirectly); Assert.NotEqual(parameterTypesIndexer.Parameters.Last().Type, parameterTypesIndexer.GetMethod.Parameters.Last().Type); var returnTypeIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnType"); Assert.True(returnTypeIndexer.IsIndexer); Assert.True(returnTypeIndexer.MustCallMethodsDirectly); Assert.NotEqual(returnTypeIndexer.Type, returnTypeIndexer.GetMethod.ReturnType); var parameterModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterModopt"); Assert.True(parameterModoptIndexer.IsIndexer); Assert.False(parameterModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in parameter type) Assert.NotEqual(parameterModoptIndexer.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length, parameterModoptIndexer.GetMethod.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length); var returnTypeModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnTypeModopt"); Assert.True(returnTypeModoptIndexer.IsIndexer); Assert.False(returnTypeModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in return type) Assert.NotEqual(returnTypeModoptIndexer.TypeWithAnnotations.CustomModifiers.Length, returnTypeModoptIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Length); }); } [ClrOnlyFact] public void LoadParameterNames() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } // NB: getter and setter have different parameter names .method public hidebysig specialname instance void set_Item(int32 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 ReadWrite(int32) { .get instance int32 C::get_Item(int32) .set instance void C::set_Item(int32, int32) } .property instance int32 ReadOnly(int32) { .get instance int32 C::get_Item(int32) } .property instance int32 WriteOnly(int32) { .set instance void C::set_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var property1 = @class.GetMember<PEPropertySymbol>("ReadWrite"); var property1ParamName = property1.Parameters.Single().Name; // NOTE: prefer setter Assert.NotEqual(property1ParamName, property1.GetMethod.Parameters.Single().Name); Assert.Equal(property1ParamName, property1.SetMethod.Parameters.First().Name); var property2 = @class.GetMember<PEPropertySymbol>("ReadOnly"); var property2ParamName = property2.Parameters.Single().Name; Assert.Equal(property2ParamName, property2.GetMethod.Parameters.Single().Name); var property3 = @class.GetMember<PEPropertySymbol>("WriteOnly"); var property3ParamName = property3.Parameters.Single().Name; Assert.Equal(property3ParamName, property3.SetMethod.Parameters.First().Name); }); } /// <remarks> /// Only testing parameter count mismatch. There isn't specific handling for other /// types of bogus properties - just setter param name if setter available and getter /// param name if getter available (i.e. same as success case). /// </remarks> [ClrOnlyFact] public void LoadBogusParameterNames() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Item(int32 x, int32 y) cil managed { ldc.i4.0 ret } // accessor has too many parameters .property instance int32 TooMany(int32) { .get instance int32 C::get_Item(int32, int32) } // accessor has too few parameters .property instance int32 TooFew(int32, int32, int32) { .get instance int32 C::get_Item(int32, int32) } } "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var accessor = @class.GetMember<MethodSymbol>("get_Item"); var accessParam0Name = accessor.Parameters[0].Name; var accessParam1Name = accessor.Parameters[1].Name; var property1 = @class.GetMember<PEPropertySymbol>("TooMany"); Assert.Equal(accessParam0Name, property1.Parameters[0].Name); var property2 = @class.GetMember<PEPropertySymbol>("TooFew"); var property2Params = property2.Parameters; Assert.Equal(accessParam0Name, property2Params[0].Name); Assert.Equal(accessParam1Name, property2Params[1].Name); Assert.Equal("value", property2Params[2].Name); //filler name }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadParamArrayAttribute() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('accessor')} .method public hidebysig specialname instance int32 accessor(int32[] a) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ldc.i4.0 ret } .method public hidebysig specialname instance void accessor(int32[] a, int32 'value') cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 ReadWrite(int32[]) { .get instance int32 C::accessor(int32[]) .set instance void C::accessor(int32[], int32) } .property instance int32 ReadOnly(int32[]) { .get instance int32 C::accessor(int32[]) } .property instance int32 WriteOnly(int32[]) { .set instance void C::accessor(int32[], int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var readWrite = @class.GetIndexer<PEPropertySymbol>("ReadWrite"); Assert.True(readWrite.IsIndexer); Assert.False(readWrite.MustCallMethodsDirectly); Assert.True(readWrite.Parameters.Last().IsParams); var readOnly = @class.GetIndexer<PEPropertySymbol>("ReadOnly"); Assert.True(readOnly.IsIndexer); Assert.False(readOnly.MustCallMethodsDirectly); Assert.True(readOnly.Parameters.Last().IsParams); var writeOnly = @class.GetIndexer<PEPropertySymbol>("WriteOnly"); Assert.True(writeOnly.IsIndexer); Assert.False(writeOnly.MustCallMethodsDirectly); Assert.True(writeOnly.Parameters.Last().IsParams); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadBogusParamArrayAttribute() { string ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('params')} .method public hidebysig specialname instance int32 params(int32[] a) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ldc.i4.0 ret } .method public hidebysig specialname instance int32 noParams(int32[] a) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void params(int32[] a, int32 'value') cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } .method public hidebysig specialname instance void noParams(int32[] a, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 OnlyGetter(int32[]) { .get instance int32 C::params(int32[]) .set instance void C::noParams(int32[], int32) } .property instance int32 OnlySetter(int32[]) { .get instance int32 C::noParams(int32[]) .set instance void C::params(int32[], int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var readWrite = @class.GetIndexer<PEPropertySymbol>("OnlyGetter"); Assert.True(readWrite.IsIndexer); Assert.True(readWrite.MustCallMethodsDirectly); Assert.False(readWrite.Parameters.Last().IsParams); //favour setter var readOnly = @class.GetIndexer<PEPropertySymbol>("OnlySetter"); Assert.True(readWrite.IsIndexer); Assert.True(readOnly.MustCallMethodsDirectly); Assert.True(readOnly.Parameters.Last().IsParams); //favour setter }); } private static void CheckIndexer(PropertySymbol indexer, bool expectGetter, bool expectSetter, string indexerDisplayString, bool suppressAssociatedPropertyCheck = false) { CheckParameterizedProperty(indexer, expectGetter, expectSetter, indexerDisplayString, true, suppressAssociatedPropertyCheck); } private static void CheckNonIndexer(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString) { CheckParameterizedProperty(property, expectGetter, expectSetter, propertyDisplayString, false, true); } private static void CheckParameterizedProperty(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString, bool expectIndexer, bool suppressAssociatedPropertyCheck) { Assert.Equal(SymbolKind.Property, property.Kind); Assert.Equal(expectIndexer, property.IsIndexer); Assert.NotEqual(expectIndexer, property.MustCallMethodsDirectly); Assert.Equal(propertyDisplayString, property.ToTestDisplayString()); if (expectGetter) { CheckAccessorShape(property.GetMethod, true, property, expectIndexer, suppressAssociatedPropertyCheck); } else { Assert.Null(property.GetMethod); } if (expectSetter) { CheckAccessorShape(property.SetMethod, false, property, expectIndexer, suppressAssociatedPropertyCheck); } else { Assert.Null(property.SetMethod); } } private static void CheckAccessorShape(MethodSymbol accessor, bool accessorIsGetMethod, PropertySymbol property, bool propertyIsIndexer, bool suppressAssociatedPropertyCheck) { Assert.NotNull(accessor); if (propertyIsIndexer) { if (!suppressAssociatedPropertyCheck) { Assert.Same(property, accessor.AssociatedSymbol); } } else { Assert.Null(accessor.AssociatedSymbol); Assert.Equal(MethodKind.Ordinary, accessor.MethodKind); } if (accessorIsGetMethod) { Assert.Equal(propertyIsIndexer ? MethodKind.PropertyGet : MethodKind.Ordinary, accessor.MethodKind); Assert.Equal(property.Type, accessor.ReturnType); Assert.Equal(property.ParameterCount, accessor.ParameterCount); } else { Assert.Equal(propertyIsIndexer ? MethodKind.PropertySet : MethodKind.Ordinary, accessor.MethodKind); Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); Assert.Equal(property.Type, accessor.Parameters.Last().Type); Assert.Equal(property.ParameterCount + 1, accessor.ParameterCount); } // NOTE: won't check last param of setter - that was handled above. for (int i = 0; i < property.ParameterCount; i++) { Assert.Equal(property.Parameters[i].Type, accessor.Parameters[i].Type); } Assert.Equal(property.IsAbstract, accessor.IsAbstract); Assert.Equal(property.IsOverride, @accessor.IsOverride); Assert.Equal(property.IsVirtual, @accessor.IsVirtual); Assert.Equal(property.IsSealed, @accessor.IsSealed); Assert.Equal(property.IsExtern, @accessor.IsExtern); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void LoadExplicitImplementation() { string ilSource = @" .class interface public abstract auto ansi I { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32 x) cil managed { } // end of method I::get_Item .method public hidebysig newslot specialname abstract virtual instance void set_Item(int32 x, int32 'value') cil managed { } // end of method I::set_Item .property instance int32 Item(int32) { .get instance int32 I::get_Item(int32) .set instance void I::set_Item(int32, int32) } // end of property I::Item } // end of class I .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements I { .method private hidebysig newslot specialname virtual final instance int32 I.get_Item(int32 x) cil managed { .override I::get_Item ldnull throw } .method private hidebysig newslot specialname virtual final instance void I.set_Item(int32 x, int32 'value') cil managed { .override I::set_Item ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 I.Item(int32) { .get instance int32 C::I.get_Item(int32) .set instance void C::I.set_Item(int32, int32) } } // end of class C "; CompileWithCustomILSource("", ilSource, compilation => { var @interface = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("I"); var interfaceIndexer = @interface.Indexers.Single(); Assert.True(interfaceIndexer.IsIndexer); var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C"); var classIndexer = (PropertySymbol)@class.GetMembers().Single(s => s.Kind == SymbolKind.Property); Assert.False(classIndexer.IsIndexer); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexer)); Assert.Equal(interfaceIndexer, classIndexer.ExplicitInterfaceImplementations.Single()); }); } [Fact] public void LoadImplicitImplementation() { } [Fact] public void LoadOverriding() { } [Fact] public void LoadHiding() { } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocSpanExpressionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StackAllocSpanExpressionsTests : CompilingTestBase { [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = (Test)stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { double x = stackalloc int[10]; // implicit short y = (short)stackalloc int[10]; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[10]; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[10]; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[10]").WithArguments("int", "short").WithLocation(7, 19)); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a = stackalloc int [10]; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,23): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [10]").WithArguments("System.Span`1").WithLocation(6, 23)); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a = stackalloc int [10]; } } }").VerifyEmitDiagnostics( // (11,27): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [10]").WithArguments("System.Span`1", ".ctor").WithLocation(11, 27)); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x = true ? stackalloc int [10] : stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,46): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [5]").WithArguments("short", "System.Span<int>").WithLocation(7, 46)); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a = stackalloc int [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x = true ? stackalloc int [10] : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [10] : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 17) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int [1] : stackalloc int [2] : N() ? stackalloc int[3] : N() ? stackalloc int[4] : stackalloc int[5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { var source = @" class Test { void M() { if(stackalloc int[10] == stackalloc int[10]) { } } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,12): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 12), // (6,34): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 34) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,12): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[10] == stackalloc int[10]").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 12) ); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Statements() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,23): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater. // Span<int> x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 23)); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Expressions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" class Test { void M(bool condition) { var x = condition ? stackalloc int[10] : stackalloc int[100]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // ? stackalloc int[10] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 15), // (8,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // : stackalloc int[100]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[100]").WithArguments("ref structs", "7.2").WithLocation(8, 15)); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(6, 17)); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v = stackalloc int[1]").WithArguments("System.Span<int>").WithLocation(6, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,39): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "System.IDisposable").WithLocation(6, 39)); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p = stackalloc int[1]; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15)); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p = stackalloc int[1]").WithLocation(7, 23), // (7,27): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 27)); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = ref stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,31): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 31) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,31): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 31) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int[1]); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[1]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length = (stackalloc int [10]).Length; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length = (stackalloc int [10]).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 23) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [10]); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [10]").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { var d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (6,33): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(6, 28)); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { Span<dynamic> d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (7,38): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 38)); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int[10]").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x = (stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = (stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x = stackalloc int[1] ?? stackalloc int[2]; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,17): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 17), // (6,38): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 38) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,17): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[1] ?? stackalloc int[2]").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 17) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value = true ? new Test() : (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] [WorkItem(25038, "https://github.com/dotnet/roslyn/issues/25038")] public void StackAllocToSpanWithRefStructType() { CreateCompilationWithMscorlibAndSpan(@" using System; ref struct S {} class Test { void M() { Span<S> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; } }").VerifyDiagnostics( // (8,14): error CS0306: The type 'S' may not be used as a type argument // Span<S> explicitError = default; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S").WithArguments("S").WithLocation(8, 14), // (9,67): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[10]").WithArguments("S").WithLocation(9, 67), // (9,86): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[100]").WithArguments("S").WithLocation(9, 86) ); } [Fact] [WorkItem(25086, "https://github.com/dotnet/roslyn/issues/25086")] public void StaackAllocToSpanWithCustomSpanAndConstraints() { var code = @" using System; namespace System { public unsafe readonly ref struct Span<T> where T : IComparable { public Span(void* ptr, int length) { Length = length; } public int Length { get; } } } struct NonComparable { } class Test { void M() { Span<NonComparable> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; } }"; var references = new List<MetadataReference>() { MscorlibRef_v4_0_30316_17626, SystemCoreRef, CSharpRef }; CreateEmptyCompilation(code, references, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (19,14): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // Span<NonComparable> explicitError = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(19, 14), // (20,67): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[10]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 67), // (20,98): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[100]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 98)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToPointer() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(int* value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(int* value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToSpan() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(System.Span<int> value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(System.Span<int> value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StackAllocSpanExpressionsTests : CompilingTestBase { [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = (Test)stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { double x = stackalloc int[10]; // implicit short y = (short)stackalloc int[10]; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[10]; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[10]; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[10]").WithArguments("int", "short").WithLocation(7, 19)); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a = stackalloc int [10]; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,23): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [10]").WithArguments("System.Span`1").WithLocation(6, 23)); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a = stackalloc int [10]; } } }").VerifyEmitDiagnostics( // (11,27): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [10]").WithArguments("System.Span`1", ".ctor").WithLocation(11, 27)); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x = true ? stackalloc int [10] : stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,46): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [5]").WithArguments("short", "System.Span<int>").WithLocation(7, 46)); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a = stackalloc int [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x = true ? stackalloc int [10] : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [10] : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 17) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int [1] : stackalloc int [2] : N() ? stackalloc int[3] : N() ? stackalloc int[4] : stackalloc int[5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { var source = @" class Test { void M() { if(stackalloc int[10] == stackalloc int[10]) { } } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,12): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 12), // (6,34): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 34) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,12): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[10] == stackalloc int[10]").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 12) ); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Statements() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,23): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater. // Span<int> x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 23)); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Expressions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" class Test { void M(bool condition) { var x = condition ? stackalloc int[10] : stackalloc int[100]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // ? stackalloc int[10] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 15), // (8,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // : stackalloc int[100]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[100]").WithArguments("ref structs", "7.2").WithLocation(8, 15)); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(6, 17)); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v = stackalloc int[1]").WithArguments("System.Span<int>").WithLocation(6, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,39): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "System.IDisposable").WithLocation(6, 39)); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p = stackalloc int[1]; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15)); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p = stackalloc int[1]").WithLocation(7, 23), // (7,27): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 27)); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = ref stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,31): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 31) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,31): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 31) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int[1]); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[1]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length = (stackalloc int [10]).Length; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length = (stackalloc int [10]).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 23) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [10]); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [10]").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { var d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (6,33): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(6, 28)); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { Span<dynamic> d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (7,38): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 38)); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int[10]").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x = (stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = (stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x = stackalloc int[1] ?? stackalloc int[2]; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,17): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 17), // (6,38): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 38) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,17): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[1] ?? stackalloc int[2]").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 17) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value = true ? new Test() : (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] [WorkItem(25038, "https://github.com/dotnet/roslyn/issues/25038")] public void StackAllocToSpanWithRefStructType() { CreateCompilationWithMscorlibAndSpan(@" using System; ref struct S {} class Test { void M() { Span<S> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; } }").VerifyDiagnostics( // (8,14): error CS0306: The type 'S' may not be used as a type argument // Span<S> explicitError = default; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S").WithArguments("S").WithLocation(8, 14), // (9,67): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[10]").WithArguments("S").WithLocation(9, 67), // (9,86): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[100]").WithArguments("S").WithLocation(9, 86) ); } [Fact] [WorkItem(25086, "https://github.com/dotnet/roslyn/issues/25086")] public void StaackAllocToSpanWithCustomSpanAndConstraints() { var code = @" using System; namespace System { public unsafe readonly ref struct Span<T> where T : IComparable { public Span(void* ptr, int length) { Length = length; } public int Length { get; } } } struct NonComparable { } class Test { void M() { Span<NonComparable> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; } }"; var references = new List<MetadataReference>() { MscorlibRef_v4_0_30316_17626, SystemCoreRef, CSharpRef }; CreateEmptyCompilation(code, references, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (19,14): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // Span<NonComparable> explicitError = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(19, 14), // (20,67): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[10]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 67), // (20,98): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[100]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 98)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToPointer() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(int* value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(int* value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToSpan() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(System.Span<int> value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(System.Span<int> value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Features/Core/Portable/Completion/Providers/AbstractEmbeddedLanguageCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { /// <summary> /// The singular completion provider that will hook into completion and will /// provider all completions across all embedded languages. /// /// Completions for an individual language are provided by /// <see cref="IEmbeddedLanguageFeatures.CompletionProvider"/>. /// </summary> internal abstract class AbstractEmbeddedLanguageCompletionProvider : LSPCompletionProvider { public const string EmbeddedProviderName = "EmbeddedProvider"; private ImmutableArray<IEmbeddedLanguage> _languageProviders; protected AbstractEmbeddedLanguageCompletionProvider(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices, string languageName) { var embeddedLanguageServiceType = typeof(IEmbeddedLanguagesProvider).AssemblyQualifiedName; TriggerCharacters = languageServices .Where(lazyLanguageService => IsEmbeddedLanguageProvider(lazyLanguageService, languageName, embeddedLanguageServiceType)) .SelectMany(lazyLanguageService => ((IEmbeddedLanguagesProvider)lazyLanguageService.Value).Languages) .SelectMany(GetTriggerCharactersForEmbeddedLanguage) .ToImmutableHashSet(); } private static ImmutableHashSet<char> GetTriggerCharactersForEmbeddedLanguage(IEmbeddedLanguage language) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider is LSPCompletionProvider lspCompletionProvider) { return lspCompletionProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } private static bool IsEmbeddedLanguageProvider(Lazy<ILanguageService, LanguageServiceMetadata> lazyLanguageService, string languageName, string? embeddedLanguageServiceType) { return lazyLanguageService.Metadata.Language == languageName && lazyLanguageService.Metadata.ServiceType == embeddedLanguageServiceType; } protected ImmutableArray<IEmbeddedLanguage> GetLanguageProviders(HostLanguageServices? languageServices) { if (_languageProviders.IsDefault) { var languagesProvider = languageServices?.GetService<IEmbeddedLanguagesProvider>(); ImmutableInterlocked.InterlockedInitialize(ref _languageProviders, languagesProvider?.Languages ?? ImmutableArray<IEmbeddedLanguage>.Empty); } return _languageProviders; } public override ImmutableHashSet<char> TriggerCharacters { get; } internal override bool ShouldTriggerCompletion(HostLanguageServices? languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { foreach (var language in GetLanguageProviders(languageServices)) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider != null) { if (completionProvider.ShouldTriggerCompletion( text, caretPosition, trigger, options)) { return true; } } } return false; } public override async Task ProvideCompletionsAsync(CompletionContext context) { foreach (var language in GetLanguageProviders(context.Document.Project.LanguageServices)) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider != null) { var count = context.Items.Count; await completionProvider.ProvideCompletionsAsync(context).ConfigureAwait(false); if (context.Items.Count > count) { return; } } } } public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => GetLanguage(item).CompletionProvider.GetChangeAsync(document, item, commitKey, cancellationToken); public override Task<CompletionDescription?> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => GetLanguage(item).CompletionProvider.GetDescriptionAsync(document, item, cancellationToken); private IEmbeddedLanguageFeatures GetLanguage(CompletionItem item) { if (_languageProviders.IsDefault) throw ExceptionUtilities.Unreachable; return (IEmbeddedLanguageFeatures)_languageProviders.Single(lang => (lang as IEmbeddedLanguageFeatures)?.CompletionProvider?.Name == item.Properties[EmbeddedProviderName]); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { /// <summary> /// The singular completion provider that will hook into completion and will /// provider all completions across all embedded languages. /// /// Completions for an individual language are provided by /// <see cref="IEmbeddedLanguageFeatures.CompletionProvider"/>. /// </summary> internal abstract class AbstractEmbeddedLanguageCompletionProvider : LSPCompletionProvider { public const string EmbeddedProviderName = "EmbeddedProvider"; private ImmutableArray<IEmbeddedLanguage> _languageProviders; protected AbstractEmbeddedLanguageCompletionProvider(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices, string languageName) { var embeddedLanguageServiceType = typeof(IEmbeddedLanguagesProvider).AssemblyQualifiedName; TriggerCharacters = languageServices .Where(lazyLanguageService => IsEmbeddedLanguageProvider(lazyLanguageService, languageName, embeddedLanguageServiceType)) .SelectMany(lazyLanguageService => ((IEmbeddedLanguagesProvider)lazyLanguageService.Value).Languages) .SelectMany(GetTriggerCharactersForEmbeddedLanguage) .ToImmutableHashSet(); } private static ImmutableHashSet<char> GetTriggerCharactersForEmbeddedLanguage(IEmbeddedLanguage language) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider is LSPCompletionProvider lspCompletionProvider) { return lspCompletionProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } private static bool IsEmbeddedLanguageProvider(Lazy<ILanguageService, LanguageServiceMetadata> lazyLanguageService, string languageName, string? embeddedLanguageServiceType) { return lazyLanguageService.Metadata.Language == languageName && lazyLanguageService.Metadata.ServiceType == embeddedLanguageServiceType; } protected ImmutableArray<IEmbeddedLanguage> GetLanguageProviders(HostLanguageServices? languageServices) { if (_languageProviders.IsDefault) { var languagesProvider = languageServices?.GetService<IEmbeddedLanguagesProvider>(); ImmutableInterlocked.InterlockedInitialize(ref _languageProviders, languagesProvider?.Languages ?? ImmutableArray<IEmbeddedLanguage>.Empty); } return _languageProviders; } public override ImmutableHashSet<char> TriggerCharacters { get; } internal override bool ShouldTriggerCompletion(HostLanguageServices? languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { foreach (var language in GetLanguageProviders(languageServices)) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider != null) { if (completionProvider.ShouldTriggerCompletion( text, caretPosition, trigger, options)) { return true; } } } return false; } public override async Task ProvideCompletionsAsync(CompletionContext context) { foreach (var language in GetLanguageProviders(context.Document.Project.LanguageServices)) { var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider; if (completionProvider != null) { var count = context.Items.Count; await completionProvider.ProvideCompletionsAsync(context).ConfigureAwait(false); if (context.Items.Count > count) { return; } } } } public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => GetLanguage(item).CompletionProvider.GetChangeAsync(document, item, commitKey, cancellationToken); public override Task<CompletionDescription?> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => GetLanguage(item).CompletionProvider.GetDescriptionAsync(document, item, cancellationToken); private IEmbeddedLanguageFeatures GetLanguage(CompletionItem item) { if (_languageProviders.IsDefault) throw ExceptionUtilities.Unreachable; return (IEmbeddedLanguageFeatures)_languageProviders.Single(lang => (lang as IEmbeddedLanguageFeatures)?.CompletionProvider?.Name == item.Properties[EmbeddedProviderName]); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Compilers/CSharp/Test/Syntax/Parsing/DeclarationExpressionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.Tuples)] public class DeclarationExpressionTests : ParsingTests { public DeclarationExpressionTests(ITestOutputHelper output) : base(output) { } [Fact] public void NullaboutOutDeclaration() { UsingStatement("M(out int? x);"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableTypeTest_01() { UsingStatement("if (e is int?) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_02() { UsingStatement("if (e is int ? true : false) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.ColonToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_03() { UsingStatement("if (e is int? x) {}", // (1,16): error CS1003: Syntax error, ':' expected // if (e is int? x) {} Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(1, 16), // (1,16): error CS1525: Invalid expression term ')' // if (e is int? x) {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 16) ); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_04() { UsingStatement("if (e is int x ? true : false) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.ColonToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_05() { UsingStatement("ref object x = o1 is string ? ref o2 : ref o3;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o1"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o2"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o3"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableTypeTest_06() { UsingStatement("ref object x = ref o1 is string ? ref o2 : ref o3;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o1"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o2"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o3"); } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void UnderscoreInOldForeach_01() { UsingStatement("foreach (int _ in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "_"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void UnderscoreInOldForeach_02() { UsingStatement("foreach (var _ in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.IdentifierToken, "_"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_01() { UsingStatement("foreach ((var x, var y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_02() { UsingStatement("foreach ((int x, int y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_03() { UsingStatement("foreach ((int x, int y) v in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "v"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_04() { // there are semantic, not syntax errors UsingStatement("foreach ((1, 2) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_05() { UsingStatement("foreach (var (x, y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_06() { UsingStatement("foreach ((int x, var (y, z)) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_07() { // there are semantic but not syntax errors here. UsingStatement("foreach ((var (x, y), z) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_08() { UsingStatement("foreach (x in e) {}", // (1,12): error CS0230: Type and identifier are both required in a foreach statement // foreach (x in e) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 12) ); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_09() { UsingStatement("foreach (_ in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_10() { UsingStatement("foreach (a.b in e) {}", // (1,14): error CS0230: Type and identifier are both required in a foreach statement // foreach (a.b in e) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 14) ); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void TupleOnTheLeft() { UsingStatement("(1, 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_01() { UsingStatement("M(out (1, 2));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_02() { UsingStatement("M(out (x, y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_03() { UsingStatement("M(out (1, 2).Field);"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Field"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_04() { // there are semantic but not syntax errors here. UsingStatement("M(out (int x, int y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_05() { // there are semantic but not syntax errors here. UsingStatement("M(out (var x, var y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NamedTupleOnTheLeft() { UsingStatement("(x: 1, y: 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void InvokeMethodNamedVar() { UsingStatement("var(1, 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.Tuples)] public class DeclarationExpressionTests : ParsingTests { public DeclarationExpressionTests(ITestOutputHelper output) : base(output) { } [Fact] public void NullaboutOutDeclaration() { UsingStatement("M(out int? x);"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableTypeTest_01() { UsingStatement("if (e is int?) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_02() { UsingStatement("if (e is int ? true : false) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.ColonToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_03() { UsingStatement("if (e is int? x) {}", // (1,16): error CS1003: Syntax error, ':' expected // if (e is int? x) {} Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(1, 16), // (1,16): error CS1525: Invalid expression term ')' // if (e is int? x) {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 16) ); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_04() { UsingStatement("if (e is int x ? true : false) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.ColonToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableTypeTest_05() { UsingStatement("ref object x = o1 is string ? ref o2 : ref o3;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o1"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o2"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o3"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableTypeTest_06() { UsingStatement("ref object x = ref o1 is string ? ref o2 : ref o3;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o1"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o2"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o3"); } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void UnderscoreInOldForeach_01() { UsingStatement("foreach (int _ in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "_"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void UnderscoreInOldForeach_02() { UsingStatement("foreach (var _ in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.IdentifierToken, "_"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_01() { UsingStatement("foreach ((var x, var y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_02() { UsingStatement("foreach ((int x, int y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_03() { UsingStatement("foreach ((int x, int y) v in e) {}"); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "v"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_04() { // there are semantic, not syntax errors UsingStatement("foreach ((1, 2) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_05() { UsingStatement("foreach (var (x, y) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_06() { UsingStatement("foreach ((int x, var (y, z)) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "z"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_07() { // there are semantic but not syntax errors here. UsingStatement("foreach ((var (x, y), z) in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_08() { UsingStatement("foreach (x in e) {}", // (1,12): error CS0230: Type and identifier are both required in a foreach statement // foreach (x in e) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 12) ); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_09() { UsingStatement("foreach (_ in e) {}"); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NewForeach_10() { UsingStatement("foreach (a.b in e) {}", // (1,14): error CS0230: Type and identifier are both required in a foreach statement // foreach (a.b in e) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 14) ); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void TupleOnTheLeft() { UsingStatement("(1, 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_01() { UsingStatement("M(out (1, 2));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_02() { UsingStatement("M(out (x, y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_03() { UsingStatement("M(out (1, 2).Field);"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Field"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_04() { // there are semantic but not syntax errors here. UsingStatement("M(out (int x, int y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OutTuple_05() { // there are semantic but not syntax errors here. UsingStatement("M(out (var x, var y));"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NamedTupleOnTheLeft() { UsingStatement("(x: 1, y: 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void InvokeMethodNamedVar() { UsingStatement("var(1, 2) = e;"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/IImportCompletionCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface IImportCompletionCacheService<TProject, TPortableExecutable> : IWorkspaceService { // PE references are keyed on assembly path. IDictionary<string, TPortableExecutable> PEItemsCache { get; } IDictionary<ProjectId, TProject> ProjectItemsCache { 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.Generic; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface IImportCompletionCacheService<TProject, TPortableExecutable> : IWorkspaceService { // PE references are keyed on assembly path. IDictionary<string, TPortableExecutable> PEItemsCache { get; } IDictionary<ProjectId, TProject> ProjectItemsCache { get; } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertBetweenRegularAndVerbatimString { public class ConvertBetweenRegularAndVerbatimStringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyRegularString() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = @""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]""; } } ", @" class Test { void Method() { var v = """"; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = // leading @""[||]"" /* trailing */; } } ", @" class Test { void Method() { var v = // leading """" /* trailing */; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithBasicText() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithBasicText() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""; } } ", @" class Test { void Method() { var v = ""a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithUnicodeEscape() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]\u0001""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\nb""; } } ", @" class Test { void Method() { var v = @""a b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a b""; } } ", @" class Test { void Method() { var v = ""a\r\nb""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNull() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a\0b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\""b""; } } ", @" class Test { void Method() { var v = @""a""""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""""b""; } } ", @" class Test { void Method() { var v = ""a\""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInRegularString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\n{1}""; } } ", @" class Test { void Method() { var v = @""a {1}""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a {1}""; } } ", @" class Test { void Method() { var v = ""a\r\n{1}""; } } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertBetweenRegularAndVerbatimString { public class ConvertBetweenRegularAndVerbatimStringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyRegularString() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = @""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]""; } } ", @" class Test { void Method() { var v = """"; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = // leading @""[||]"" /* trailing */; } } ", @" class Test { void Method() { var v = // leading """" /* trailing */; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithBasicText() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithBasicText() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""; } } ", @" class Test { void Method() { var v = ""a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithUnicodeEscape() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]\u0001""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\nb""; } } ", @" class Test { void Method() { var v = @""a b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a b""; } } ", @" class Test { void Method() { var v = ""a\r\nb""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNull() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a\0b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\""b""; } } ", @" class Test { void Method() { var v = @""a""""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""""b""; } } ", @" class Test { void Method() { var v = ""a\""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInRegularString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\n{1}""; } } ", @" class Test { void Method() { var v = @""a {1}""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a {1}""; } } ", @" class Test { void Method() { var v = ""a\r\n{1}""; } } "); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/VisualStudio/Core/Def/Implementation/Library/AbstractLibraryManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal abstract partial class AbstractLibraryManager : IVsCoTaskMemFreeMyStrings { internal readonly Guid LibraryGuid; private readonly IServiceProvider _serviceProvider; private readonly IntPtr _imageListPtr; protected AbstractLibraryManager(Guid libraryGuid, IServiceProvider serviceProvider) { LibraryGuid = libraryGuid; _serviceProvider = serviceProvider; var vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell; vsShell?.TryGetPropertyValue(__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out _imageListPtr); } public IServiceProvider ServiceProvider { get { return _serviceProvider; } } public IntPtr ImageListPtr { get { return _imageListPtr; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal abstract partial class AbstractLibraryManager : IVsCoTaskMemFreeMyStrings { internal readonly Guid LibraryGuid; private readonly IServiceProvider _serviceProvider; private readonly IntPtr _imageListPtr; protected AbstractLibraryManager(Guid libraryGuid, IServiceProvider serviceProvider) { LibraryGuid = libraryGuid; _serviceProvider = serviceProvider; var vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell; vsShell?.TryGetPropertyValue(__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out _imageListPtr); } public IServiceProvider ServiceProvider { get { return _serviceProvider; } } public IntPtr ImageListPtr { get { return _imageListPtr; } } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/Core.Cocoa/NavigationCommandHandlers/FindDerivedSymbolsCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(FindDerivedSymbolsCommandHandler))] internal sealed class FindDerivedSymbolsCommandHandler : AbstractNavigationCommandHandler<FindDerivedSymbolsCommandArgs> { private readonly IAsynchronousOperationListener _asyncListener; public override string DisplayName => nameof(FindDerivedSymbolsCommandHandler); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindDerivedSymbolsCommandHandler( [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters, IAsynchronousOperationListenerProvider listenerProvider) : base(streamingPresenters) { Contract.ThrowIfNull(listenerProvider); _asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences); } protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context) { var streamingPresenter = base.GetStreamingPresenter(); if (streamingPresenter != null) { _ = FindDerivedSymbolsAsync(document, caretPosition, streamingPresenter); return true; } return false; } private static async Task<IEnumerable<ISymbol>> GatherSymbolsAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // if the symbol is in an interface, or if it is an interface // we can use the FindInterfaceImplementationAsync call if (symbol.ContainingType is INamedTypeSymbol namedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Interface) { return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol, solution, null, cancellationToken).ConfigureAwait(false); } else if (symbol is INamedTypeSymbol namedTypeSymbol2 && namedTypeSymbol2.TypeKind == TypeKind.Interface) { return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol2, solution, null, cancellationToken).ConfigureAwait(false); } // if it's not, but is instead a class, we can use FindDerivedClassesAsync else if (symbol is INamedTypeSymbol namedTypeSymbol3) { return await SymbolFinder.FindDerivedClassesAsync(namedTypeSymbol3, solution, null, cancellationToken).ConfigureAwait(false); } // and lastly, if it's a method, we can use FindOverridesAsync else { return await SymbolFinder.FindOverridesAsync(symbol, solution, null, cancellationToken).ConfigureAwait(false); } } private async Task FindDerivedSymbolsAsync( Document document, int caretPosition, IStreamingFindUsagesPresenter presenter) { try { using var token = _asyncListener.BeginAsyncOperation(nameof(FindDerivedSymbolsAsync)); var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true); try { using (Logger.LogBlock( FunctionId.CommandHandler_FindAllReference, KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"), cancellationToken)) { var candidateSymbolProjectPair = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); if (candidateSymbolProjectPair?.symbol == null) return; var candidates = await GatherSymbolsAsync(candidateSymbolProjectPair.Value.symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false); foreach (var candidate in candidates) { var definitionItem = candidate.ToNonClassifiedDefinitionItem(document.Project.Solution, true); await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); } } } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(FindDerivedSymbolsCommandHandler))] internal sealed class FindDerivedSymbolsCommandHandler : AbstractNavigationCommandHandler<FindDerivedSymbolsCommandArgs> { private readonly IAsynchronousOperationListener _asyncListener; public override string DisplayName => nameof(FindDerivedSymbolsCommandHandler); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindDerivedSymbolsCommandHandler( [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters, IAsynchronousOperationListenerProvider listenerProvider) : base(streamingPresenters) { Contract.ThrowIfNull(listenerProvider); _asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences); } protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context) { var streamingPresenter = base.GetStreamingPresenter(); if (streamingPresenter != null) { _ = FindDerivedSymbolsAsync(document, caretPosition, streamingPresenter); return true; } return false; } private static async Task<IEnumerable<ISymbol>> GatherSymbolsAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // if the symbol is in an interface, or if it is an interface // we can use the FindInterfaceImplementationAsync call if (symbol.ContainingType is INamedTypeSymbol namedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Interface) { return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol, solution, null, cancellationToken).ConfigureAwait(false); } else if (symbol is INamedTypeSymbol namedTypeSymbol2 && namedTypeSymbol2.TypeKind == TypeKind.Interface) { return await SymbolFinder.FindImplementationsAsync(namedTypeSymbol2, solution, null, cancellationToken).ConfigureAwait(false); } // if it's not, but is instead a class, we can use FindDerivedClassesAsync else if (symbol is INamedTypeSymbol namedTypeSymbol3) { return await SymbolFinder.FindDerivedClassesAsync(namedTypeSymbol3, solution, null, cancellationToken).ConfigureAwait(false); } // and lastly, if it's a method, we can use FindOverridesAsync else { return await SymbolFinder.FindOverridesAsync(symbol, solution, null, cancellationToken).ConfigureAwait(false); } } private async Task FindDerivedSymbolsAsync( Document document, int caretPosition, IStreamingFindUsagesPresenter presenter) { try { using var token = _asyncListener.BeginAsyncOperation(nameof(FindDerivedSymbolsAsync)); var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true); try { using (Logger.LogBlock( FunctionId.CommandHandler_FindAllReference, KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"), cancellationToken)) { var candidateSymbolProjectPair = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); if (candidateSymbolProjectPair?.symbol == null) return; var candidates = await GatherSymbolsAsync(candidateSymbolProjectPair.Value.symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false); foreach (var candidate in candidates) { var definitionItem = candidate.ToNonClassifiedDefinitionItem(document.Project.Solution, true); await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); } } } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/Core/MSBuild/MSBuild/DiagnosticReportingMode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.MSBuild { internal enum DiagnosticReportingMode { Throw, Log, Ignore } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.MSBuild { internal enum DiagnosticReportingMode { Throw, Log, Ignore } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/ArrayExpansionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ArrayExpansionTests : CSharpResultProviderTestBase { [Fact] public void Array() { var rootExpr = "new[] { 1, 2, 3 }"; var value = CreateDkmClrValue(new[] { 1, 2, 3 }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3]}", "int[]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "(new[] { 1, 2, 3 })[0]"), EvalResult("[1]", "2", "int", "(new[] { 1, 2, 3 })[1]"), EvalResult("[2]", "3", "int", "(new[] { 1, 2, 3 })[2]")); } [Fact] public void ZeroLengthArray() { var rootExpr = "new object[0]"; var value = CreateDkmClrValue(new object[0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{object[0]}", "object[]", rootExpr)); DkmEvaluationResultEnumContext enumContext; var children = GetChildren(evalResult, 100, null, out enumContext); Verify(children); var items = GetItems(enumContext, 0, enumContext.Count); Verify(items); } [Fact] public void NestedArray() { var rootExpr = "new int[][] { new[] { 1, 2 }, new[] { 3 } }"; var value = CreateDkmClrValue(new int[][] { new[] { 1, 2 }, new[] { 3 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2][]}", "int[][]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "{int[2]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0]", DkmEvaluationResultFlags.Expandable), EvalResult("[1]", "{int[1]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "1", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][0]"), EvalResult("[1]", "2", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][1]")); Verify(GetChildren(children[1]), EvalResult("[0]", "3", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1][0]")); } [Fact] public void MultiDimensionalArray() { var rootExpr = "new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }"; var value = CreateDkmClrValue(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3, 2]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0, 0]", "1", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 0]"), EvalResult("[0, 1]", "2", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 1]"), EvalResult("[1, 0]", "3", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 0]"), EvalResult("[1, 1]", "4", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 1]"), EvalResult("[2, 0]", "5", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 0]"), EvalResult("[2, 1]", "6", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 1]")); } [Fact] public void ZeroLengthMultiDimensionalArray() { var rootExpr = "new int[2, 3, 0]"; var value = CreateDkmClrValue(new int[2, 3, 0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 3, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[2, 0, 3]"; value = CreateDkmClrValue(new int[2, 0, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 0, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 2, 3]"; value = CreateDkmClrValue(new int[0, 2, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 2, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 0, 0]"; value = CreateDkmClrValue(new int[0, 0, 0]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 0, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); } [Fact] public void NullArray() { var rootExpr = "new int[][,,] { null, new int[2, 3, 4] }"; var evalResult = FormatResult(rootExpr, CreateDkmClrValue(new int[][,,] { null, new int[2, 3, 4] })); Verify(evalResult, EvalResult(rootExpr, "{int[2][,,]}", "int[][,,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[0]"), EvalResult("[1]", "{int[2, 3, 4]}", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[1]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BaseType() { var source = @"class C { object o = new int[] { 1, 2 }; System.Array a = new object[] { null }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{object[1]}", "System.Array {object[]}", "(new C()).a", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("o", "{int[2]}", "object {int[]}", "(new C()).o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[0]), EvalResult("[0]", "null", "object", "((object[])(new C()).a)[0]")); Verify(GetChildren(children[1]), EvalResult("[0]", "1", "int", "((int[])(new C()).o)[0]"), EvalResult("[1]", "2", "int", "((int[])(new C()).o)[1]")); } [WorkItem(933845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933845")] [Fact] public void BaseElementType() { var source = @"class A { internal object F; } class B : A { internal B(object f) { F = f; } internal object P { get { return this.F; } } }"; var assembly = GetAssembly(source); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue(new object[] { 1, typeB.Instantiate(2) }); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{object[2]}", "object[]", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "object {int}", "o[0]"), EvalResult("[1]", "{B}", "object {B}", "o[1]", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[1]); Verify(children, EvalResult("F", "2", "object {int}", "((A)o[1]).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "2", "object {int}", "((B)o[1]).P", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); } [WorkItem(1022157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022157")] [Fact] public void Covariance() { var source = @"interface I { } class A { object F = 1; } class B : A, I { } class C { object[] F = new[] { new A() }; A[] G = new[] { new B() }; I[] H = new[] { new B() }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{A[1]}", "object[] {A[]}", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{B[1]}", "A[] {B[]}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("H", "{B[1]}", "I[] {B[]}", "o.H", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "{A}", "object {A}", "((A[])o.F)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "1", "object {int}", "((A)((A[])o.F)[0]).F", DkmEvaluationResultFlags.CanFavorite)); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "{B}", "A {B}", "((B[])o.G)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult("[0]", "{B}", "I {B}", "((B[])o.H)[0]", DkmEvaluationResultFlags.Expandable)); } [WorkItem(1001844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1001844")] [Fact] public void Interface() { var source = @"class C { char[] F = new char[] { '1' }; System.Collections.IEnumerable G = new char[] { '2' }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{char[1]}", "char[]", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "49 '1'", "char", "o.F[0]", editableValue: "'1'")); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "50 '2'", "char", "((char[])o.G)[0]", editableValue: "'2'")); } [Fact] public void NonZeroLowerBounds() { var rootExpr = "arrayExpr"; var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 3 }, new[] { 3, 4 }); array[3, 4] = 1; array[3, 5] = 2; array[3, 6] = 3; array[4, 4] = 4; array[4, 5] = 5; array[4, 6] = 6; var value = CreateDkmClrValue(array); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3..4, 4..6]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[3, 4]", "1", "int", "arrayExpr[3, 4]"), EvalResult("[3, 5]", "2", "int", "arrayExpr[3, 5]"), EvalResult("[3, 6]", "3", "int", "arrayExpr[3, 6]"), EvalResult("[4, 4]", "4", "int", "arrayExpr[4, 4]"), EvalResult("[4, 5]", "5", "int", "arrayExpr[4, 5]"), EvalResult("[4, 6]", "6", "int", "arrayExpr[4, 6]")); } [Fact] public void Hexadecimal() { var value = CreateDkmClrValue(new[] { 10, 20, 30 }); var inspectionContext = CreateDkmInspectionContext(radix: 16); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("o", "{int[0x00000003]}", "int[]", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext); // Hex could be used for indices: [0x00000000], etc. Verify(children, EvalResult("[0]", "0x0000000a", "int", "o[0]"), EvalResult("[1]", "0x00000014", "int", "o[1]"), EvalResult("[2]", "0x0000001e", "int", "o[2]")); } [Fact] public void HexadecimalNonZeroLowerBounds() { var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 1 }, new[] { -3, 4 }); array[-3, 4] = 1; array[-2, 4] = 2; var value = CreateDkmClrValue(array); var inspectionContext = CreateDkmInspectionContext(radix: 16); var evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{int[0xfffffffd..0xfffffffe, 0x00000004..0x00000004]}", "int[,]", "a", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext); // Hex could be used for indices: [0xfffffffd, 0x00000004], etc. Verify(children, EvalResult("[-3, 4]", "0x00000001", "int", "a[-3, 4]"), EvalResult("[-2, 4]", "0x00000002", "int", "a[-2, 4]")); } /// <summary> /// Expansion should be lazy so that the IDE can /// reduce overhead by expanding a subset of rows. /// </summary> [Fact] public void LazyExpansion() { var rootExpr = "new byte[10, 1000, 1000]"; var parenthesizedExpr = string.Format("({0})", rootExpr); var value = CreateDkmClrValue(new byte[10, 1000, 1000]); // Array with 10M elements var evalResults = new DkmEvaluationResult[100]; // 100 distinct evaluations of the array for (int i = 0; i < evalResults.Length; i++) { var evalResult = FormatResult(rootExpr, value); evalResults[i] = evalResult; // Expand a subset. int offset = i * 100 * 1000; DkmEvaluationResultEnumContext enumContext; GetChildren(evalResult, 0, null, out enumContext); var items = GetItems(enumContext, offset, 2); var indices1 = string.Format("{0}, {1}, {2}", offset / 1000000, (offset % 1000000) / 1000, 0); var indices2 = string.Format("{0}, {1}, {2}", (offset + 1) / 1000000, ((offset + 1) % 1000000) / 1000, 1); Verify(items, EvalResult(string.Format("[{0}]", indices1), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices1)), EvalResult(string.Format("[{0}]", indices2), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices2))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ArrayExpansionTests : CSharpResultProviderTestBase { [Fact] public void Array() { var rootExpr = "new[] { 1, 2, 3 }"; var value = CreateDkmClrValue(new[] { 1, 2, 3 }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3]}", "int[]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "(new[] { 1, 2, 3 })[0]"), EvalResult("[1]", "2", "int", "(new[] { 1, 2, 3 })[1]"), EvalResult("[2]", "3", "int", "(new[] { 1, 2, 3 })[2]")); } [Fact] public void ZeroLengthArray() { var rootExpr = "new object[0]"; var value = CreateDkmClrValue(new object[0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{object[0]}", "object[]", rootExpr)); DkmEvaluationResultEnumContext enumContext; var children = GetChildren(evalResult, 100, null, out enumContext); Verify(children); var items = GetItems(enumContext, 0, enumContext.Count); Verify(items); } [Fact] public void NestedArray() { var rootExpr = "new int[][] { new[] { 1, 2 }, new[] { 3 } }"; var value = CreateDkmClrValue(new int[][] { new[] { 1, 2 }, new[] { 3 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2][]}", "int[][]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "{int[2]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0]", DkmEvaluationResultFlags.Expandable), EvalResult("[1]", "{int[1]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "1", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][0]"), EvalResult("[1]", "2", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][1]")); Verify(GetChildren(children[1]), EvalResult("[0]", "3", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1][0]")); } [Fact] public void MultiDimensionalArray() { var rootExpr = "new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }"; var value = CreateDkmClrValue(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3, 2]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0, 0]", "1", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 0]"), EvalResult("[0, 1]", "2", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 1]"), EvalResult("[1, 0]", "3", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 0]"), EvalResult("[1, 1]", "4", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 1]"), EvalResult("[2, 0]", "5", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 0]"), EvalResult("[2, 1]", "6", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 1]")); } [Fact] public void ZeroLengthMultiDimensionalArray() { var rootExpr = "new int[2, 3, 0]"; var value = CreateDkmClrValue(new int[2, 3, 0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 3, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[2, 0, 3]"; value = CreateDkmClrValue(new int[2, 0, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 0, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 2, 3]"; value = CreateDkmClrValue(new int[0, 2, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 2, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 0, 0]"; value = CreateDkmClrValue(new int[0, 0, 0]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 0, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); } [Fact] public void NullArray() { var rootExpr = "new int[][,,] { null, new int[2, 3, 4] }"; var evalResult = FormatResult(rootExpr, CreateDkmClrValue(new int[][,,] { null, new int[2, 3, 4] })); Verify(evalResult, EvalResult(rootExpr, "{int[2][,,]}", "int[][,,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[0]"), EvalResult("[1]", "{int[2, 3, 4]}", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[1]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BaseType() { var source = @"class C { object o = new int[] { 1, 2 }; System.Array a = new object[] { null }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{object[1]}", "System.Array {object[]}", "(new C()).a", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("o", "{int[2]}", "object {int[]}", "(new C()).o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[0]), EvalResult("[0]", "null", "object", "((object[])(new C()).a)[0]")); Verify(GetChildren(children[1]), EvalResult("[0]", "1", "int", "((int[])(new C()).o)[0]"), EvalResult("[1]", "2", "int", "((int[])(new C()).o)[1]")); } [WorkItem(933845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933845")] [Fact] public void BaseElementType() { var source = @"class A { internal object F; } class B : A { internal B(object f) { F = f; } internal object P { get { return this.F; } } }"; var assembly = GetAssembly(source); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue(new object[] { 1, typeB.Instantiate(2) }); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{object[2]}", "object[]", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "object {int}", "o[0]"), EvalResult("[1]", "{B}", "object {B}", "o[1]", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[1]); Verify(children, EvalResult("F", "2", "object {int}", "((A)o[1]).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "2", "object {int}", "((B)o[1]).P", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite)); } [WorkItem(1022157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022157")] [Fact] public void Covariance() { var source = @"interface I { } class A { object F = 1; } class B : A, I { } class C { object[] F = new[] { new A() }; A[] G = new[] { new B() }; I[] H = new[] { new B() }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{A[1]}", "object[] {A[]}", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{B[1]}", "A[] {B[]}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("H", "{B[1]}", "I[] {B[]}", "o.H", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "{A}", "object {A}", "((A[])o.F)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "1", "object {int}", "((A)((A[])o.F)[0]).F", DkmEvaluationResultFlags.CanFavorite)); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "{B}", "A {B}", "((B[])o.G)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult("[0]", "{B}", "I {B}", "((B[])o.H)[0]", DkmEvaluationResultFlags.Expandable)); } [WorkItem(1001844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1001844")] [Fact] public void Interface() { var source = @"class C { char[] F = new char[] { '1' }; System.Collections.IEnumerable G = new char[] { '2' }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{char[1]}", "char[]", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("G", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o.G", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "49 '1'", "char", "o.F[0]", editableValue: "'1'")); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "50 '2'", "char", "((char[])o.G)[0]", editableValue: "'2'")); } [Fact] public void NonZeroLowerBounds() { var rootExpr = "arrayExpr"; var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 3 }, new[] { 3, 4 }); array[3, 4] = 1; array[3, 5] = 2; array[3, 6] = 3; array[4, 4] = 4; array[4, 5] = 5; array[4, 6] = 6; var value = CreateDkmClrValue(array); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3..4, 4..6]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[3, 4]", "1", "int", "arrayExpr[3, 4]"), EvalResult("[3, 5]", "2", "int", "arrayExpr[3, 5]"), EvalResult("[3, 6]", "3", "int", "arrayExpr[3, 6]"), EvalResult("[4, 4]", "4", "int", "arrayExpr[4, 4]"), EvalResult("[4, 5]", "5", "int", "arrayExpr[4, 5]"), EvalResult("[4, 6]", "6", "int", "arrayExpr[4, 6]")); } [Fact] public void Hexadecimal() { var value = CreateDkmClrValue(new[] { 10, 20, 30 }); var inspectionContext = CreateDkmInspectionContext(radix: 16); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("o", "{int[0x00000003]}", "int[]", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext); // Hex could be used for indices: [0x00000000], etc. Verify(children, EvalResult("[0]", "0x0000000a", "int", "o[0]"), EvalResult("[1]", "0x00000014", "int", "o[1]"), EvalResult("[2]", "0x0000001e", "int", "o[2]")); } [Fact] public void HexadecimalNonZeroLowerBounds() { var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 1 }, new[] { -3, 4 }); array[-3, 4] = 1; array[-2, 4] = 2; var value = CreateDkmClrValue(array); var inspectionContext = CreateDkmInspectionContext(radix: 16); var evalResult = FormatResult("a", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("a", "{int[0xfffffffd..0xfffffffe, 0x00000004..0x00000004]}", "int[,]", "a", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext); // Hex could be used for indices: [0xfffffffd, 0x00000004], etc. Verify(children, EvalResult("[-3, 4]", "0x00000001", "int", "a[-3, 4]"), EvalResult("[-2, 4]", "0x00000002", "int", "a[-2, 4]")); } /// <summary> /// Expansion should be lazy so that the IDE can /// reduce overhead by expanding a subset of rows. /// </summary> [Fact] public void LazyExpansion() { var rootExpr = "new byte[10, 1000, 1000]"; var parenthesizedExpr = string.Format("({0})", rootExpr); var value = CreateDkmClrValue(new byte[10, 1000, 1000]); // Array with 10M elements var evalResults = new DkmEvaluationResult[100]; // 100 distinct evaluations of the array for (int i = 0; i < evalResults.Length; i++) { var evalResult = FormatResult(rootExpr, value); evalResults[i] = evalResult; // Expand a subset. int offset = i * 100 * 1000; DkmEvaluationResultEnumContext enumContext; GetChildren(evalResult, 0, null, out enumContext); var items = GetItems(enumContext, offset, 2); var indices1 = string.Format("{0}, {1}, {2}", offset / 1000000, (offset % 1000000) / 1000, 0); var indices2 = string.Format("{0}, {1}, {2}", (offset + 1) / 1000000, ((offset + 1) % 1000000) / 1000, 1); Verify(items, EvalResult(string.Format("[{0}]", indices1), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices1)), EvalResult(string.Format("[{0}]", indices2), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices2))); } } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/VisualBasic/BraceMatching/AbstractVisualBasicBraceMatcher.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching Friend Class AbstractVisualBasicBraceMatcher Inherits AbstractBraceMatcher Protected Sub New(openBrace As SyntaxKind, closeBrace As SyntaxKind) MyBase.New(New BraceCharacterAndKind(SyntaxFacts.GetText(openBrace)(0), openBrace), New BraceCharacterAndKind(SyntaxFacts.GetText(closeBrace)(0), closeBrace)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching Friend Class AbstractVisualBasicBraceMatcher Inherits AbstractBraceMatcher Protected Sub New(openBrace As SyntaxKind, closeBrace As SyntaxKind) MyBase.New(New BraceCharacterAndKind(SyntaxFacts.GetText(openBrace)(0), openBrace), New BraceCharacterAndKind(SyntaxFacts.GetText(closeBrace)(0), closeBrace)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptBreakpointResolutionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(IBreakpointResolutionService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptBreakpointResolutionService : IBreakpointResolutionService { private readonly IVSTypeScriptBreakpointResolutionServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptBreakpointResolutionService(IVSTypeScriptBreakpointResolutionServiceImplementation implementation) => _implementation = implementation; public async Task<BreakpointResolutionResult?> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken = default) => (await _implementation.ResolveBreakpointAsync(document, textSpan, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken = default) => (await _implementation.ResolveBreakpointsAsync(solution, name, cancellationToken).ConfigureAwait(false)).Select(r => r.UnderlyingObject); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(IBreakpointResolutionService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptBreakpointResolutionService : IBreakpointResolutionService { private readonly IVSTypeScriptBreakpointResolutionServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptBreakpointResolutionService(IVSTypeScriptBreakpointResolutionServiceImplementation implementation) => _implementation = implementation; public async Task<BreakpointResolutionResult?> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken = default) => (await _implementation.ResolveBreakpointAsync(document, textSpan, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken = default) => (await _implementation.ResolveBreakpointsAsync(solution, name, cancellationToken).ConfigureAwait(false)).Select(r => r.UnderlyingObject); } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/Core/MSBuild/MSBuild/CSharp/CSharpProjectFileLoaderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; namespace Microsoft.CodeAnalysis.CSharp { [Shared] [ExportLanguageServiceFactory(typeof(IProjectFileLoader), LanguageNames.CSharp)] [ProjectFileExtension("csproj")] internal class CSharpProjectFileLoaderFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectFileLoaderFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpProjectFileLoader(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; namespace Microsoft.CodeAnalysis.CSharp { [Shared] [ExportLanguageServiceFactory(typeof(IProjectFileLoader), LanguageNames.CSharp)] [ProjectFileExtension("csproj")] internal class CSharpProjectFileLoaderFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectFileLoaderFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpProjectFileLoader(); } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/VisualStudio/Core/Def/Implementation/Options/RoamingVisualStudioProfileOptionPersister.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: 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.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Workspaces/Core/MSBuild/MSBuild/MSBuildWorkspace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new(); private readonly MSBuildProjectLoader _loader; private readonly ProjectFileLoaderRegistry _projectFileLoaderRegistry; private readonly DiagnosticReporter _reporter; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, WorkspaceKind.MSBuild) { _reporter = new DiagnosticReporter(this); _projectFileLoaderRegistry = new ProjectFileLoaderRegistry(Services, _reporter); _loader = new MSBuildProjectLoader(Services, _reporter, _projectFileLoaderRegistry, properties); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, MSBuildMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(HostServices hostServices) { return Create(ImmutableDictionary<string, string>.Empty, hostServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties => _loader.Properties; /// <summary> /// Diagnostics logged while opening solutions, projects and documents. /// </summary> public ImmutableList<WorkspaceDiagnostic> Diagnostics => _reporter.Diagnostics; protected internal override void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) { _reporter.AddDiagnostic(diagnostic); base.OnWorkspaceFailed(diagnostic); } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get { return _loader.LoadMetadataForReferencedProjects; } set { _loader.LoadMetadataForReferencedProjects = value; } } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get => _loader.SkipUnrecognizedProjects; set => _loader.SkipUnrecognizedProjects = value; } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { _loader.AssociateFileExtensionWithLanguage(projectFileExtension, language); } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } private static string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is opened.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public Task<Solution> OpenSolutionAsync( #pragma warning restore RS0026 string solutionFilePath, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) => OpenSolutionAsync(solutionFilePath, msbuildLogger: null, progress, cancellationToken); /// <summary> /// Open a solution file and all referenced projects. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is opened.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public async Task<Solution> OpenSolutionAsync( #pragma warning restore RS0026 string solutionFilePath, ILogger? msbuildLogger, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var solutionInfo = await _loader.LoadSolutionInfoAsync(solutionFilePath, progress, msbuildLogger, cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos this.OnSolutionAdded(solutionInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> /// <param name="projectFilePath">The path to the project file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is opened.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public Task<Project> OpenProjectAsync( #pragma warning restore RS0026 string projectFilePath, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) => OpenProjectAsync(projectFilePath, msbuildLogger: null, progress, cancellationToken); /// <summary> /// Open a project file and all referenced projects. /// </summary> /// <param name="projectFilePath">The path to the project file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is opened.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results..</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public async Task<Project> OpenProjectAsync( #pragma warning restore RS0026 string projectFilePath, ILogger? msbuildLogger, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var projectMap = ProjectMap.Create(this.CurrentSolution); var projects = await _loader.LoadProjectInfoAsync(projectFilePath, projectMap, progress, msbuildLogger, cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in projects) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); var projectResult = this.CurrentSolution.GetProject(projects[0].Id); RoslynDebug.AssertNotNull(projectResult); return projectResult; } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { return feature is ApplyChangesKind.ChangeDocument or ApplyChangesKind.AddDocument or ApplyChangesKind.RemoveDocument or ApplyChangesKind.AddMetadataReference or ApplyChangesKind.RemoveMetadataReference or ApplyChangesKind.AddProjectReference or ApplyChangesKind.RemoveProjectReference or ApplyChangesKind.AddAnalyzerReference or ApplyChangesKind.RemoveAnalyzerReference or ApplyChangesKind.ChangeAdditionalDocument; } private static bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile? _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { return TryApplyChanges(newSolution, new ProgressTracker()); } internal override bool TryApplyChanges(Solution newSolution, IProgressTracker progressTracker) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution, progressTracker); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; if (projectPath is null) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, string.Format(WorkspaceMSBuildResources.Project_path_for_0_was_null, project.Name), projectChanges.ProjectId)); return; } if (_projectFileLoaderRegistry.TryGetLoaderFromProjectPath(projectPath, out var fileLoader)) { try { var buildManager = new ProjectBuildManager(_loader.Properties); _applyChangesProjectFile = fileLoader.LoadProjectFileAsync(projectPath, buildManager, CancellationToken.None).Result; } catch (IOException exception) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (IOException exception) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { var encoding = DetermineEncoding(text, document); if (document.FilePath is null) { var message = string.Format(WorkspaceMSBuildResources.Path_for_document_0_was_null, document.Name); _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, document.Id)); return; } this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetAdditionalDocument(documentId); if (document != null) { var encoding = DetermineEncoding(text, document); if (document.FilePath is null) { var message = string.Format(WorkspaceMSBuildResources.Path_for_additional_document_0_was_null, document.Name); _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, document.Id)); return; } this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnAdditionalDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding? DetermineEncoding(SourceText text, TextDocument document) { if (text.Encoding != null) { return text.Encoding; } try { if (document.FilePath is null) { return null; } using var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); var filePath = project?.FilePath; if (filePath is null) { return; } if (_projectFileLoaderRegistry.TryGetLoaderFromProjectPath(filePath, out _)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(filePath)!); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using var writer = new StreamWriter(fullPath, append: false, encoding: encoding); newText.Write(writer); } catch (IOException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document?.FilePath is not null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { RoslynDebug.AssertNotNull(_applyChangesProjectFile); var identity = GetAssemblyIdentity(projectId, metadataReference); if (identity is null) { var message = string.Format(WorkspaceMSBuildResources.Unable_to_add_metadata_reference_0, metadataReference.Display); _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, message, projectId)); return; } _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { RoslynDebug.AssertNotNull(_applyChangesProjectFile); var identity = GetAssemblyIdentity(projectId, metadataReference); if (identity is null) { var message = string.Format(WorkspaceMSBuildResources.Unable_to_remove_metadata_reference_0, metadataReference.Display); _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, message, projectId)); return; } _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity? GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (project is null) { return null; } if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); if (compilation is null) { return null; } var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol?.Identity; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project?.FilePath is not null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project?.FilePath is not null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new(); private readonly MSBuildProjectLoader _loader; private readonly ProjectFileLoaderRegistry _projectFileLoaderRegistry; private readonly DiagnosticReporter _reporter; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, WorkspaceKind.MSBuild) { _reporter = new DiagnosticReporter(this); _projectFileLoaderRegistry = new ProjectFileLoaderRegistry(Services, _reporter); _loader = new MSBuildProjectLoader(Services, _reporter, _projectFileLoaderRegistry, properties); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, MSBuildMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(HostServices hostServices) { return Create(ImmutableDictionary<string, string>.Empty, hostServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties => _loader.Properties; /// <summary> /// Diagnostics logged while opening solutions, projects and documents. /// </summary> public ImmutableList<WorkspaceDiagnostic> Diagnostics => _reporter.Diagnostics; protected internal override void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) { _reporter.AddDiagnostic(diagnostic); base.OnWorkspaceFailed(diagnostic); } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get { return _loader.LoadMetadataForReferencedProjects; } set { _loader.LoadMetadataForReferencedProjects = value; } } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get => _loader.SkipUnrecognizedProjects; set => _loader.SkipUnrecognizedProjects = value; } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { _loader.AssociateFileExtensionWithLanguage(projectFileExtension, language); } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } private static string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is opened.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public Task<Solution> OpenSolutionAsync( #pragma warning restore RS0026 string solutionFilePath, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) => OpenSolutionAsync(solutionFilePath, msbuildLogger: null, progress, cancellationToken); /// <summary> /// Open a solution file and all referenced projects. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is opened.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public async Task<Solution> OpenSolutionAsync( #pragma warning restore RS0026 string solutionFilePath, ILogger? msbuildLogger, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var solutionInfo = await _loader.LoadSolutionInfoAsync(solutionFilePath, progress, msbuildLogger, cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos this.OnSolutionAdded(solutionInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> /// <param name="projectFilePath">The path to the project file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is opened.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public Task<Project> OpenProjectAsync( #pragma warning restore RS0026 string projectFilePath, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) => OpenProjectAsync(projectFilePath, msbuildLogger: null, progress, cancellationToken); /// <summary> /// Open a project file and all referenced projects. /// </summary> /// <param name="projectFilePath">The path to the project file to be opened. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is opened.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results..</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> #pragma warning disable RS0026 // Special case to avoid ILogger type getting loaded in downstream clients public async Task<Project> OpenProjectAsync( #pragma warning restore RS0026 string projectFilePath, ILogger? msbuildLogger, IProgress<ProjectLoadProgress>? progress = null, CancellationToken cancellationToken = default) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var projectMap = ProjectMap.Create(this.CurrentSolution); var projects = await _loader.LoadProjectInfoAsync(projectFilePath, projectMap, progress, msbuildLogger, cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in projects) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); var projectResult = this.CurrentSolution.GetProject(projects[0].Id); RoslynDebug.AssertNotNull(projectResult); return projectResult; } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { return feature is ApplyChangesKind.ChangeDocument or ApplyChangesKind.AddDocument or ApplyChangesKind.RemoveDocument or ApplyChangesKind.AddMetadataReference or ApplyChangesKind.RemoveMetadataReference or ApplyChangesKind.AddProjectReference or ApplyChangesKind.RemoveProjectReference or ApplyChangesKind.AddAnalyzerReference or ApplyChangesKind.RemoveAnalyzerReference or ApplyChangesKind.ChangeAdditionalDocument; } private static bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile? _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { return TryApplyChanges(newSolution, new ProgressTracker()); } internal override bool TryApplyChanges(Solution newSolution, IProgressTracker progressTracker) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution, progressTracker); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; if (projectPath is null) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, string.Format(WorkspaceMSBuildResources.Project_path_for_0_was_null, project.Name), projectChanges.ProjectId)); return; } if (_projectFileLoaderRegistry.TryGetLoaderFromProjectPath(projectPath, out var fileLoader)) { try { var buildManager = new ProjectBuildManager(_loader.Properties); _applyChangesProjectFile = fileLoader.LoadProjectFileAsync(projectPath, buildManager, CancellationToken.None).Result; } catch (IOException exception) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (IOException exception) { _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { var encoding = DetermineEncoding(text, document); if (document.FilePath is null) { var message = string.Format(WorkspaceMSBuildResources.Path_for_document_0_was_null, document.Name); _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, document.Id)); return; } this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetAdditionalDocument(documentId); if (document != null) { var encoding = DetermineEncoding(text, document); if (document.FilePath is null) { var message = string.Format(WorkspaceMSBuildResources.Path_for_additional_document_0_was_null, document.Name); _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, document.Id)); return; } this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnAdditionalDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding? DetermineEncoding(SourceText text, TextDocument document) { if (text.Encoding != null) { return text.Encoding; } try { if (document.FilePath is null) { return null; } using var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); var filePath = project?.FilePath; if (filePath is null) { return; } if (_projectFileLoaderRegistry.TryGetLoaderFromProjectPath(filePath, out _)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(filePath)!); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using var writer = new StreamWriter(fullPath, append: false, encoding: encoding); newText.Write(writer); } catch (IOException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document?.FilePath is not null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { _reporter.Report(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { RoslynDebug.AssertNotNull(_applyChangesProjectFile); var identity = GetAssemblyIdentity(projectId, metadataReference); if (identity is null) { var message = string.Format(WorkspaceMSBuildResources.Unable_to_add_metadata_reference_0, metadataReference.Display); _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, message, projectId)); return; } _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { RoslynDebug.AssertNotNull(_applyChangesProjectFile); var identity = GetAssemblyIdentity(projectId, metadataReference); if (identity is null) { var message = string.Format(WorkspaceMSBuildResources.Unable_to_remove_metadata_reference_0, metadataReference.Display); _reporter.Report(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, message, projectId)); return; } _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity? GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (project is null) { return null; } if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); if (compilation is null) { return null; } var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol?.Identity; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project?.FilePath is not null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project?.FilePath is not null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #endregion }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Compilers/Test/Resources/Core/SymbolsTests/V1/MTTestLib2.Dll
MZ@ !L!This program cannot be run in DOS mode. $PELlM! n/ @@ @/W@`  H.textt  `.rsrc@@@.reloc `@BP/H " ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *0  +*( *BSJB v4.0.30319l8#~#Strings #US #GUID L#BlobW %3&    N N$~ R+ j /}^)7:7 E7 O ] x  1 1:-1\:1G!]P X `   *( S5 qB Fc!Fh4!lP!Fqh!x!!!!!"" AQY$,4<$,4<aiq yTch)aq qD]LJLTL )/.".+@+@CCI@cci"+{s++++ + @@+``++++++Y]hm||OTNY^g  uu s -w-<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class4Class4_1Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceMTTestLib1Class1FooBarSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMTTestLib2MTTestLib2.Dll bA*@n$pz\V4?_ :        0 (  %  MyTemplate10.0.0.0   My.WebServices My.User My.ComputerMy.ApplicationA  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__    TWrapNonExceptionThrows</^/ P/_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMTTestLib2.Dll(LegalCopyright HOriginalFilenameMTTestLib2.Dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 p?
MZ@ !L!This program cannot be run in DOS mode. $PELlM! n/ @@ @/W@`  H.textt  `.rsrc@@@.reloc `@BP/H " ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *0  +*( *BSJB v4.0.30319l8#~#Strings #US #GUID L#BlobW %3&    N N$~ R+ j /}^)7:7 E7 O ] x  1 1:-1\:1G!]P X `   *( S5 qB Fc!Fh4!lP!Fqh!x!!!!!"" AQY$,4<$,4<aiq yTch)aq qD]LJLTL )/.".+@+@CCI@cci"+{s++++ + @@+``++++++Y]hm||OTNY^g  uu s -w-<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class4Class4_1Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceMTTestLib1Class1FooBarSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMTTestLib2MTTestLib2.Dll bA*@n$pz\V4?_ :        0 (  %  MyTemplate10.0.0.0   My.WebServices My.User My.ComputerMy.ApplicationA  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__    TWrapNonExceptionThrows</^/ P/_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMTTestLib2.Dll(LegalCopyright HOriginalFilenameMTTestLib2.Dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 p?
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/IGenerateConversionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 IGenerateConversionService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateConversionAsync(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 IGenerateConversionService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateConversionAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/XML/ReadTree.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. '----------------------------------------------------------------------------------------------------------- 'Reads the tree from an XML file into a ParseTree object and sub-objects. Reports many kinds of errors 'during the reading process. '----------------------------------------------------------------------------------------------------------- Imports System.IO Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Xml Imports System.Xml.Schema Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler"> Public Module ReadTree Private s_currentFile As String ' Read an XML file and return the resulting ParseTree object. Public Function TryReadTheTree(fileName As String, <Out> ByRef tree As ParseTree) As Boolean tree = Nothing Dim validationError As Boolean = False Dim xDoc = GetXDocument(fileName, validationError) If validationError Then Return False End If tree = New ParseTree Dim x = xDoc.<define-parse-tree> tree.FileName = fileName tree.NamespaceName = xDoc.<define-parse-tree>.@namespace tree.VisitorName = xDoc.<define-parse-tree>.@visitor tree.RewriteVisitorName = xDoc.<define-parse-tree>.@<rewrite-visitor> tree.FactoryClassName = xDoc.<define-parse-tree>.@<factory-class> tree.ContextualFactoryClassName = xDoc.<define-parse-tree>.@<contextual-factory-class> Dim defs = xDoc.<define-parse-tree>.<definitions> For Each struct In defs.<node-structure> If tree.NodeStructures.ContainsKey(struct.@name) Then tree.ReportError(struct, "node-structure with name ""{0}"" already defined", struct.@name) Else tree.NodeStructures.Add(struct.@name, New ParseNodeStructure(struct, tree)) End If Next For Each al In defs.<node-kind-alias> If tree.Aliases.ContainsKey(al.@name) Then tree.ReportError(al, "node-kind-alias with name ""{0}"" already defined", al.@name) Else tree.Aliases.Add(al.@name, New ParseNodeKindAlias(al, tree)) End If Next For Each en In defs.<enumeration> If tree.Enumerations.ContainsKey(en.@name) Then tree.ReportError(en, "enumeration with name ""{0}"" already defined", en.@name) Else tree.Enumerations.Add(en.@name, New ParseEnumeration(en, tree)) End If Next tree.FinishedReading() Return True End Function ' Open the input XML file as an XDocument, using the reading options that we want. ' We use a schema to validate the input. Private Function GetXDocument(fileName As String, <Out> ByRef validationError As Boolean) As XDocument s_currentFile = fileName Dim xDoc As XDocument Using schemaReader = XmlReader.Create(GetType(ReadTree).GetTypeInfo().Assembly.GetManifestResourceStream("VBSyntaxModelSchema.xsd")) Dim readerSettings As New XmlReaderSettings() readerSettings.DtdProcessing = DtdProcessing.Prohibit Dim fileStream As New FileStream(fileName, FileMode.Open, FileAccess.Read) Using reader = XmlReader.Create(fileStream, readerSettings) xDoc = XDocument.Load(reader, LoadOptions.SetLineInfo Or LoadOptions.PreserveWhitespace) End Using End Using validationError = False Return xDoc End Function End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- 'Reads the tree from an XML file into a ParseTree object and sub-objects. Reports many kinds of errors 'during the reading process. '----------------------------------------------------------------------------------------------------------- Imports System.IO Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Xml Imports System.Xml.Schema Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler"> Public Module ReadTree Private s_currentFile As String ' Read an XML file and return the resulting ParseTree object. Public Function TryReadTheTree(fileName As String, <Out> ByRef tree As ParseTree) As Boolean tree = Nothing Dim validationError As Boolean = False Dim xDoc = GetXDocument(fileName, validationError) If validationError Then Return False End If tree = New ParseTree Dim x = xDoc.<define-parse-tree> tree.FileName = fileName tree.NamespaceName = xDoc.<define-parse-tree>.@namespace tree.VisitorName = xDoc.<define-parse-tree>.@visitor tree.RewriteVisitorName = xDoc.<define-parse-tree>.@<rewrite-visitor> tree.FactoryClassName = xDoc.<define-parse-tree>.@<factory-class> tree.ContextualFactoryClassName = xDoc.<define-parse-tree>.@<contextual-factory-class> Dim defs = xDoc.<define-parse-tree>.<definitions> For Each struct In defs.<node-structure> If tree.NodeStructures.ContainsKey(struct.@name) Then tree.ReportError(struct, "node-structure with name ""{0}"" already defined", struct.@name) Else tree.NodeStructures.Add(struct.@name, New ParseNodeStructure(struct, tree)) End If Next For Each al In defs.<node-kind-alias> If tree.Aliases.ContainsKey(al.@name) Then tree.ReportError(al, "node-kind-alias with name ""{0}"" already defined", al.@name) Else tree.Aliases.Add(al.@name, New ParseNodeKindAlias(al, tree)) End If Next For Each en In defs.<enumeration> If tree.Enumerations.ContainsKey(en.@name) Then tree.ReportError(en, "enumeration with name ""{0}"" already defined", en.@name) Else tree.Enumerations.Add(en.@name, New ParseEnumeration(en, tree)) End If Next tree.FinishedReading() Return True End Function ' Open the input XML file as an XDocument, using the reading options that we want. ' We use a schema to validate the input. Private Function GetXDocument(fileName As String, <Out> ByRef validationError As Boolean) As XDocument s_currentFile = fileName Dim xDoc As XDocument Using schemaReader = XmlReader.Create(GetType(ReadTree).GetTypeInfo().Assembly.GetManifestResourceStream("VBSyntaxModelSchema.xsd")) Dim readerSettings As New XmlReaderSettings() readerSettings.DtdProcessing = DtdProcessing.Prohibit Dim fileStream As New FileStream(fileName, FileMode.Open, FileAccess.Read) Using reader = XmlReader.Create(fileStream, readerSettings) xDoc = XDocument.Load(reader, LoadOptions.SetLineInfo Or LoadOptions.PreserveWhitespace) End Using End Using validationError = False Return xDoc End Function End Module
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolution.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class OverloadResolution { private NamedTypeSymbol MakeNullable(TypeSymbol type) { return Compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(type); } public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(operand != null); Debug.Assert(result.Results.Count == 0); // We can do a table lookup for well-known problems in overload resolution. UnaryOperatorEasyOut(kind, operand, result); if (result.Results.Count > 0) { return; } // SPEC: An operation of the form op x or x op, where op is an overloadable unary operator, // SPEC: and x is an expression of type X, is processed as follows: // SPEC: The set of candidate user-defined operators provided by X for the operation operator // SPEC: op(x) is determined using the rules of 7.3.5. bool hadUserDefinedCandidate = GetUserDefinedOperators(kind, operand, result.Results, ref useSiteInfo); // SPEC: If the set of candidate user-defined operators is not empty, then this becomes the // SPEC: set of candidate operators for the operation. Otherwise, the predefined unary operator // SPEC: implementations, including their lifted forms, become the set of candidate operators // SPEC: for the operation. if (!hadUserDefinedCandidate) { result.Results.Clear(); GetAllBuiltInOperators(kind, operand, result.Results, ref useSiteInfo); } // SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators // SPEC: to select the best operator with respect to the argument list (x), and this operator // SPEC: becomes the result of the overload resolution process. If overload resolution fails // SPEC: to select a single best operator, a binding-time error occurs. UnaryOperatorOverloadResolution(operand, result, ref useSiteInfo); } // Takes a list of candidates and mutates the list to throw out the ones that are worse than // another applicable candidate. private void UnaryOperatorOverloadResolution( BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Given the set of applicable candidate function members, the best function member in that set is located. // SPEC: If the set contains only one function member, then that function member is the best function member. if (result.SingleValid()) { return; } // SPEC: Otherwise, the best function member is the one function member that is better than all other function // SPEC: members with respect to the given argument list, provided that each function member is compared to all // SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is // SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time // SPEC: error occurs. var candidates = result.Results; // Try to find a single best candidate int bestIndex = GetTheBestCandidateIndex(operand, candidates, ref useSiteInfo); if (bestIndex != -1) { // Mark all other candidates as worse for (int index = 0; index < candidates.Count; ++index) { if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex) { candidates[index] = candidates[index].Worse(); } } return; } for (int i = 1; i < candidates.Count; ++i) { if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable) { continue; } // Is this applicable operator better than every other applicable method? for (int j = 0; j < i; ++j) { if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable) { continue; } var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, operand, ref useSiteInfo); if (better == BetterResult.Left) { candidates[j] = candidates[j].Worse(); } else if (better == BetterResult.Right) { candidates[i] = candidates[i].Worse(); } } } } private int GetTheBestCandidateIndex( BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> candidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { int currentBestIndex = -1; for (int index = 0; index < candidates.Count; index++) { if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable) { continue; } // Assume that the current candidate is the best if we don't have any if (currentBestIndex == -1) { currentBestIndex = index; } else { var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, operand, ref useSiteInfo); if (better == BetterResult.Right) { // The current best is worse currentBestIndex = index; } else if (better != BetterResult.Left) { // The current best is not better currentBestIndex = -1; } } } // Make sure that every candidate up to the current best is worse for (int index = 0; index < currentBestIndex; index++) { if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable) { continue; } var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, operand, ref useSiteInfo); if (better != BetterResult.Left) { // The current best is not better return -1; } } return currentBestIndex; } private BetterResult BetterOperator(UnaryOperatorSignature op1, UnaryOperatorSignature op2, BoundExpression operand, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // First we see if the conversion from the operand to one operand type is better than // the conversion to the other. BetterResult better = BetterConversionFromExpression(operand, op1.OperandType, op2.OperandType, ref useSiteInfo); if (better == BetterResult.Left || better == BetterResult.Right) { return better; } // There was no better member on the basis of conversions. Go to the tiebreaking round. // SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi // SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules // SPEC: are applied: if (Conversions.HasIdentityConversion(op1.OperandType, op2.OperandType)) { // SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq. // Under what circumstances can two unary operators with identical signatures be "more specific" // than another? With a binary operator you could have C<T>.op+(C<T>, T) and C<T>.op+(C<T>, int). // When doing overload resolution on C<int> + int, the latter is more specific. But with a unary // operator, the sole operand *must* be the containing type or its nullable type. Therefore // if there is an identity conversion, then the parameters really were identical. We therefore // skip checking for specificity. // SPEC: If one member is a non-lifted operator and the other is a lifted operator, // SPEC: the non-lifted one is better. bool lifted1 = op1.Kind.IsLifted(); bool lifted2 = op2.Kind.IsLifted(); if (lifted1 && !lifted2) { return BetterResult.Right; } else if (!lifted1 && lifted2) { return BetterResult.Left; } } // Always prefer operators with val parameters over operators with in parameters: if (op1.RefKind == RefKind.None && op2.RefKind == RefKind.In) { return BetterResult.Left; } else if (op2.RefKind == RefKind.None && op1.RefKind == RefKind.In) { return BetterResult.Right; } return BetterResult.Neither; } private void GetAllBuiltInOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // The spec states that overload resolution is performed upon the infinite set of // operators defined on enumerated types, pointers and delegates. Clearly we cannot // construct the infinite set; we have to pare it down. Previous implementations of C# // implement a much stricter rule; they only add the special operators to the candidate // set if one of the operands is of the relevant type. This means that operands // involving user-defined implicit conversions from class or struct types to enum, // pointer and delegate types do not cause the right candidates to participate in // overload resolution. It also presents numerous problems involving delegate variance // and conversions from lambdas to delegate types. // // It is onerous to require the actually specified behavior. We should change the // specification to match the previous implementation. var operators = ArrayBuilder<UnaryOperatorSignature>.GetInstance(); this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators, skipNativeIntegerOperators: !operand.Type.IsNativeIntegerOrNullableNativeIntegerType()); GetEnumOperations(kind, operand, operators); var pointerOperator = GetPointerOperation(kind, operand); if (pointerOperator != null) { operators.Add(pointerOperator.Value); } CandidateOperators(operators, operand, results, ref useSiteInfo); operators.Free(); } // Returns true if there were any applicable candidates. private bool CandidateOperators(ArrayBuilder<UnaryOperatorSignature> operators, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool anyApplicable = false; foreach (var op in operators) { var conversion = Conversions.ClassifyConversionFromExpression(operand, op.OperandType, ref useSiteInfo); if (conversion.IsImplicit) { anyApplicable = true; results.Add(UnaryOperatorAnalysisResult.Applicable(op, conversion)); } else { results.Add(UnaryOperatorAnalysisResult.Inapplicable(op, conversion)); } } return anyApplicable; } private void GetEnumOperations(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorSignature> operators) { Debug.Assert(operand != null); var enumType = operand.Type; if ((object)enumType == null) { return; } enumType = enumType.StrippedType(); if (!enumType.IsValidEnumType()) { return; } var nullableEnum = MakeNullable(enumType); switch (kind) { case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.BitwiseComplement: operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Enum, enumType, enumType)); operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Lifted | UnaryOperatorKind.Enum, nullableEnum, nullableEnum)); break; } } private static UnaryOperatorSignature? GetPointerOperation(UnaryOperatorKind kind, BoundExpression operand) { Debug.Assert(operand != null); var pointerType = operand.Type as PointerTypeSymbol; if ((object)pointerType == null) { return null; } UnaryOperatorSignature? op = null; switch (kind) { case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PrefixDecrement: op = new UnaryOperatorSignature(kind | UnaryOperatorKind.Pointer, pointerType, pointerType); break; } return op; } // Returns true if there were any applicable candidates. private bool GetUserDefinedOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(operand != null); if ((object)operand.Type == null) { // If the operand has no type -- because it is a null reference or a lambda or a method group -- // there is no way we can determine what type to search for user-defined operators. return false; } // Spec 7.3.5 Candidate user-defined operators // SPEC: Given a type T and an operation op(A) ... the set of candidate user-defined // SPEC: operators provided by T for op(A) is determined as follows: // SPEC: If T is a nullable type then T0 is its underlying type; otherwise T0 is T. // SPEC: For all operator declarations in T0 and all lifted forms of such operators, if // SPEC: at least one operator is applicable with respect to A then the set of candidate // SPEC: operators consists of all such applicable operators. Otherwise, if T0 is object // SPEC: then the set of candidate operators is empty. Otherwise, the set of candidate // SPEC: operators is the set provided by the direct base class of T0, or the effective // SPEC: base class of T0 if T0 is a type parameter. // https://github.com/dotnet/roslyn/issues/34451: The spec quote should be adjusted to cover operators from interfaces as well. // From https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-27.md: // - We only even look for operator implementations in interfaces if one of the operands has a type that is an interface or // a type parameter with a non-empty effective base interface list. // - The applicable operators from classes / structs shadow those in interfaces.This matters for constrained type parameters: // the effective base class can shadow operators from effective base interfaces. // - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in base interfaces: // we stop looking. TypeSymbol type0 = operand.Type.StrippedType(); TypeSymbol constrainedToTypeOpt = type0 as TypeParameterSymbol; // Searching for user-defined operators is expensive; let's take an early out if we can. if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0)) { return false; } string name = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind); var operators = ArrayBuilder<UnaryOperatorSignature>.GetInstance(); bool hadApplicableCandidates = false; NamedTypeSymbol current = type0 as NamedTypeSymbol; if ((object)current == null) { current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } if ((object)current == null && type0.IsTypeParameter()) { current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteInfo); } for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { operators.Clear(); GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, current, kind, name, operators); results.Clear(); if (CandidateOperators(operators, operand, results, ref useSiteInfo)) { hadApplicableCandidates = true; break; } } // Look in base interfaces, or effective interfaces for type parameters if (!hadApplicableCandidates) { ImmutableArray<NamedTypeSymbol> interfaces = default; if (type0.IsInterfaceType()) { interfaces = type0.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (type0.IsTypeParameter()) { interfaces = ((TypeParameterSymbol)type0).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } if (!interfaces.IsDefaultOrEmpty) { var shadowedInterfaces = PooledHashSet<NamedTypeSymbol>.GetInstance(); var resultsFromInterface = ArrayBuilder<UnaryOperatorAnalysisResult>.GetInstance(); results.Clear(); foreach (NamedTypeSymbol @interface in interfaces) { if ([email protected]) { // this code could be reachable in error situations continue; } if (shadowedInterfaces.Contains(@interface)) { // this interface is "shadowed" by a derived interface continue; } operators.Clear(); resultsFromInterface.Clear(); GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name, operators); if (CandidateOperators(operators, operand, resultsFromInterface, ref useSiteInfo)) { hadApplicableCandidates = true; results.AddRange(resultsFromInterface); // this interface "shadows" all its base interfaces shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } } shadowedInterfaces.Free(); resultsFromInterface.Free(); } } operators.Free(); return hadApplicableCandidates; } private void GetUserDefinedUnaryOperatorsFromType( TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, string name, ArrayBuilder<UnaryOperatorSignature> operators) { foreach (MethodSymbol op in type.GetOperators(name)) { // If we're in error recovery, we might have bad operators. Just ignore it. if (op.ParameterCount != 1 || op.ReturnsVoid) { continue; } TypeSymbol operandType = op.GetParameterType(0); TypeSymbol resultType = op.ReturnType; operators.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | kind, operandType, resultType, op, constrainedToTypeOpt)); // SPEC: For the unary operators + ++ - -- ! ~ a lifted form of an operator exists // SPEC: if the operand and its result types are both non-nullable value types. // SPEC: The lifted form is constructed by adding a single ? modifier to the // SPEC: operator and result types. switch (kind) { case UnaryOperatorKind.UnaryPlus: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.UnaryMinus: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.LogicalNegation: case UnaryOperatorKind.BitwiseComplement: if (operandType.IsValueType && !operandType.IsNullableType() && resultType.IsValueType && !resultType.IsNullableType()) { operators.Add(new UnaryOperatorSignature( UnaryOperatorKind.Lifted | UnaryOperatorKind.UserDefined | kind, MakeNullable(operandType), MakeNullable(resultType), op, constrainedToTypeOpt)); } break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class OverloadResolution { private NamedTypeSymbol MakeNullable(TypeSymbol type) { return Compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(type); } public void UnaryOperatorOverloadResolution(UnaryOperatorKind kind, BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(operand != null); Debug.Assert(result.Results.Count == 0); // We can do a table lookup for well-known problems in overload resolution. UnaryOperatorEasyOut(kind, operand, result); if (result.Results.Count > 0) { return; } // SPEC: An operation of the form op x or x op, where op is an overloadable unary operator, // SPEC: and x is an expression of type X, is processed as follows: // SPEC: The set of candidate user-defined operators provided by X for the operation operator // SPEC: op(x) is determined using the rules of 7.3.5. bool hadUserDefinedCandidate = GetUserDefinedOperators(kind, operand, result.Results, ref useSiteInfo); // SPEC: If the set of candidate user-defined operators is not empty, then this becomes the // SPEC: set of candidate operators for the operation. Otherwise, the predefined unary operator // SPEC: implementations, including their lifted forms, become the set of candidate operators // SPEC: for the operation. if (!hadUserDefinedCandidate) { result.Results.Clear(); GetAllBuiltInOperators(kind, operand, result.Results, ref useSiteInfo); } // SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators // SPEC: to select the best operator with respect to the argument list (x), and this operator // SPEC: becomes the result of the overload resolution process. If overload resolution fails // SPEC: to select a single best operator, a binding-time error occurs. UnaryOperatorOverloadResolution(operand, result, ref useSiteInfo); } // Takes a list of candidates and mutates the list to throw out the ones that are worse than // another applicable candidate. private void UnaryOperatorOverloadResolution( BoundExpression operand, UnaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Given the set of applicable candidate function members, the best function member in that set is located. // SPEC: If the set contains only one function member, then that function member is the best function member. if (result.SingleValid()) { return; } // SPEC: Otherwise, the best function member is the one function member that is better than all other function // SPEC: members with respect to the given argument list, provided that each function member is compared to all // SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is // SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time // SPEC: error occurs. var candidates = result.Results; // Try to find a single best candidate int bestIndex = GetTheBestCandidateIndex(operand, candidates, ref useSiteInfo); if (bestIndex != -1) { // Mark all other candidates as worse for (int index = 0; index < candidates.Count; ++index) { if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex) { candidates[index] = candidates[index].Worse(); } } return; } for (int i = 1; i < candidates.Count; ++i) { if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable) { continue; } // Is this applicable operator better than every other applicable method? for (int j = 0; j < i; ++j) { if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable) { continue; } var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, operand, ref useSiteInfo); if (better == BetterResult.Left) { candidates[j] = candidates[j].Worse(); } else if (better == BetterResult.Right) { candidates[i] = candidates[i].Worse(); } } } } private int GetTheBestCandidateIndex( BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> candidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { int currentBestIndex = -1; for (int index = 0; index < candidates.Count; index++) { if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable) { continue; } // Assume that the current candidate is the best if we don't have any if (currentBestIndex == -1) { currentBestIndex = index; } else { var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, operand, ref useSiteInfo); if (better == BetterResult.Right) { // The current best is worse currentBestIndex = index; } else if (better != BetterResult.Left) { // The current best is not better currentBestIndex = -1; } } } // Make sure that every candidate up to the current best is worse for (int index = 0; index < currentBestIndex; index++) { if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable) { continue; } var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, operand, ref useSiteInfo); if (better != BetterResult.Left) { // The current best is not better return -1; } } return currentBestIndex; } private BetterResult BetterOperator(UnaryOperatorSignature op1, UnaryOperatorSignature op2, BoundExpression operand, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // First we see if the conversion from the operand to one operand type is better than // the conversion to the other. BetterResult better = BetterConversionFromExpression(operand, op1.OperandType, op2.OperandType, ref useSiteInfo); if (better == BetterResult.Left || better == BetterResult.Right) { return better; } // There was no better member on the basis of conversions. Go to the tiebreaking round. // SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi // SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules // SPEC: are applied: if (Conversions.HasIdentityConversion(op1.OperandType, op2.OperandType)) { // SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq. // Under what circumstances can two unary operators with identical signatures be "more specific" // than another? With a binary operator you could have C<T>.op+(C<T>, T) and C<T>.op+(C<T>, int). // When doing overload resolution on C<int> + int, the latter is more specific. But with a unary // operator, the sole operand *must* be the containing type or its nullable type. Therefore // if there is an identity conversion, then the parameters really were identical. We therefore // skip checking for specificity. // SPEC: If one member is a non-lifted operator and the other is a lifted operator, // SPEC: the non-lifted one is better. bool lifted1 = op1.Kind.IsLifted(); bool lifted2 = op2.Kind.IsLifted(); if (lifted1 && !lifted2) { return BetterResult.Right; } else if (!lifted1 && lifted2) { return BetterResult.Left; } } // Always prefer operators with val parameters over operators with in parameters: if (op1.RefKind == RefKind.None && op2.RefKind == RefKind.In) { return BetterResult.Left; } else if (op2.RefKind == RefKind.None && op1.RefKind == RefKind.In) { return BetterResult.Right; } return BetterResult.Neither; } private void GetAllBuiltInOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // The spec states that overload resolution is performed upon the infinite set of // operators defined on enumerated types, pointers and delegates. Clearly we cannot // construct the infinite set; we have to pare it down. Previous implementations of C# // implement a much stricter rule; they only add the special operators to the candidate // set if one of the operands is of the relevant type. This means that operands // involving user-defined implicit conversions from class or struct types to enum, // pointer and delegate types do not cause the right candidates to participate in // overload resolution. It also presents numerous problems involving delegate variance // and conversions from lambdas to delegate types. // // It is onerous to require the actually specified behavior. We should change the // specification to match the previous implementation. var operators = ArrayBuilder<UnaryOperatorSignature>.GetInstance(); this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators, skipNativeIntegerOperators: !operand.Type.IsNativeIntegerOrNullableNativeIntegerType()); GetEnumOperations(kind, operand, operators); var pointerOperator = GetPointerOperation(kind, operand); if (pointerOperator != null) { operators.Add(pointerOperator.Value); } CandidateOperators(operators, operand, results, ref useSiteInfo); operators.Free(); } // Returns true if there were any applicable candidates. private bool CandidateOperators(ArrayBuilder<UnaryOperatorSignature> operators, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool anyApplicable = false; foreach (var op in operators) { var conversion = Conversions.ClassifyConversionFromExpression(operand, op.OperandType, ref useSiteInfo); if (conversion.IsImplicit) { anyApplicable = true; results.Add(UnaryOperatorAnalysisResult.Applicable(op, conversion)); } else { results.Add(UnaryOperatorAnalysisResult.Inapplicable(op, conversion)); } } return anyApplicable; } private void GetEnumOperations(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorSignature> operators) { Debug.Assert(operand != null); var enumType = operand.Type; if ((object)enumType == null) { return; } enumType = enumType.StrippedType(); if (!enumType.IsValidEnumType()) { return; } var nullableEnum = MakeNullable(enumType); switch (kind) { case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.BitwiseComplement: operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Enum, enumType, enumType)); operators.Add(new UnaryOperatorSignature(kind | UnaryOperatorKind.Lifted | UnaryOperatorKind.Enum, nullableEnum, nullableEnum)); break; } } private static UnaryOperatorSignature? GetPointerOperation(UnaryOperatorKind kind, BoundExpression operand) { Debug.Assert(operand != null); var pointerType = operand.Type as PointerTypeSymbol; if ((object)pointerType == null) { return null; } UnaryOperatorSignature? op = null; switch (kind) { case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PrefixDecrement: op = new UnaryOperatorSignature(kind | UnaryOperatorKind.Pointer, pointerType, pointerType); break; } return op; } // Returns true if there were any applicable candidates. private bool GetUserDefinedOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(operand != null); if ((object)operand.Type == null) { // If the operand has no type -- because it is a null reference or a lambda or a method group -- // there is no way we can determine what type to search for user-defined operators. return false; } // Spec 7.3.5 Candidate user-defined operators // SPEC: Given a type T and an operation op(A) ... the set of candidate user-defined // SPEC: operators provided by T for op(A) is determined as follows: // SPEC: If T is a nullable type then T0 is its underlying type; otherwise T0 is T. // SPEC: For all operator declarations in T0 and all lifted forms of such operators, if // SPEC: at least one operator is applicable with respect to A then the set of candidate // SPEC: operators consists of all such applicable operators. Otherwise, if T0 is object // SPEC: then the set of candidate operators is empty. Otherwise, the set of candidate // SPEC: operators is the set provided by the direct base class of T0, or the effective // SPEC: base class of T0 if T0 is a type parameter. // https://github.com/dotnet/roslyn/issues/34451: The spec quote should be adjusted to cover operators from interfaces as well. // From https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-27.md: // - We only even look for operator implementations in interfaces if one of the operands has a type that is an interface or // a type parameter with a non-empty effective base interface list. // - The applicable operators from classes / structs shadow those in interfaces.This matters for constrained type parameters: // the effective base class can shadow operators from effective base interfaces. // - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in base interfaces: // we stop looking. TypeSymbol type0 = operand.Type.StrippedType(); TypeSymbol constrainedToTypeOpt = type0 as TypeParameterSymbol; // Searching for user-defined operators is expensive; let's take an early out if we can. if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0)) { return false; } string name = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind); var operators = ArrayBuilder<UnaryOperatorSignature>.GetInstance(); bool hadApplicableCandidates = false; NamedTypeSymbol current = type0 as NamedTypeSymbol; if ((object)current == null) { current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } if ((object)current == null && type0.IsTypeParameter()) { current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteInfo); } for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { operators.Clear(); GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, current, kind, name, operators); results.Clear(); if (CandidateOperators(operators, operand, results, ref useSiteInfo)) { hadApplicableCandidates = true; break; } } // Look in base interfaces, or effective interfaces for type parameters if (!hadApplicableCandidates) { ImmutableArray<NamedTypeSymbol> interfaces = default; if (type0.IsInterfaceType()) { interfaces = type0.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (type0.IsTypeParameter()) { interfaces = ((TypeParameterSymbol)type0).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } if (!interfaces.IsDefaultOrEmpty) { var shadowedInterfaces = PooledHashSet<NamedTypeSymbol>.GetInstance(); var resultsFromInterface = ArrayBuilder<UnaryOperatorAnalysisResult>.GetInstance(); results.Clear(); foreach (NamedTypeSymbol @interface in interfaces) { if ([email protected]) { // this code could be reachable in error situations continue; } if (shadowedInterfaces.Contains(@interface)) { // this interface is "shadowed" by a derived interface continue; } operators.Clear(); resultsFromInterface.Clear(); GetUserDefinedUnaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name, operators); if (CandidateOperators(operators, operand, resultsFromInterface, ref useSiteInfo)) { hadApplicableCandidates = true; results.AddRange(resultsFromInterface); // this interface "shadows" all its base interfaces shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } } shadowedInterfaces.Free(); resultsFromInterface.Free(); } } operators.Free(); return hadApplicableCandidates; } private void GetUserDefinedUnaryOperatorsFromType( TypeSymbol constrainedToTypeOpt, NamedTypeSymbol type, UnaryOperatorKind kind, string name, ArrayBuilder<UnaryOperatorSignature> operators) { foreach (MethodSymbol op in type.GetOperators(name)) { // If we're in error recovery, we might have bad operators. Just ignore it. if (op.ParameterCount != 1 || op.ReturnsVoid) { continue; } TypeSymbol operandType = op.GetParameterType(0); TypeSymbol resultType = op.ReturnType; operators.Add(new UnaryOperatorSignature(UnaryOperatorKind.UserDefined | kind, operandType, resultType, op, constrainedToTypeOpt)); // SPEC: For the unary operators + ++ - -- ! ~ a lifted form of an operator exists // SPEC: if the operand and its result types are both non-nullable value types. // SPEC: The lifted form is constructed by adding a single ? modifier to the // SPEC: operator and result types. switch (kind) { case UnaryOperatorKind.UnaryPlus: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.UnaryMinus: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.LogicalNegation: case UnaryOperatorKind.BitwiseComplement: if (operandType.IsValueType && !operandType.IsNullableType() && resultType.IsValueType && !resultType.IsNullableType()) { operators.Add(new UnaryOperatorSignature( UnaryOperatorKind.Lifted | UnaryOperatorKind.UserDefined | kind, MakeNullable(operandType), MakeNullable(resultType), op, constrainedToTypeOpt)); } break; } } } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./eng/common/cross/toolchain.cmake
set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) if(EXISTS ${CROSS_ROOTFS}/bin/freebsd-version) set(CMAKE_SYSTEM_NAME FreeBSD) elseif(EXISTS ${CROSS_ROOTFS}/usr/platform/i86pc) set(CMAKE_SYSTEM_NAME SunOS) set(ILLUMOS 1) else() set(CMAKE_SYSTEM_NAME Linux) endif() set(CMAKE_SYSTEM_VERSION 1) if(TARGET_ARCH_NAME STREQUAL "armel") set(CMAKE_SYSTEM_PROCESSOR armv7l) set(TOOLCHAIN "arm-linux-gnueabi") if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm") set(CMAKE_SYSTEM_PROCESSOR armv7l) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv7-alpine-linux-musleabihf) set(TOOLCHAIN "armv7-alpine-linux-musleabihf") elseif(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) set(TOOLCHAIN "armv6-alpine-linux-musleabihf") else() set(TOOLCHAIN "arm-linux-gnueabihf") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(CMAKE_SYSTEM_PROCESSOR aarch64) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) set(TOOLCHAIN "aarch64-alpine-linux-musl") else() set(TOOLCHAIN "aarch64-linux-gnu") endif() if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "aarch64-tizen-linux-gnu/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "s390x") set(CMAKE_SYSTEM_PROCESSOR s390x) set(TOOLCHAIN "s390x-linux-gnu") elseif(TARGET_ARCH_NAME STREQUAL "x86") set(CMAKE_SYSTEM_PROCESSOR i686) set(TOOLCHAIN "i686-linux-gnu") elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(triple "x86_64-unknown-freebsd11") elseif (ILLUMOS) set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(TOOLCHAIN "x86_64-illumos") else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) set(TOOLCHAIN $ENV{TOOLCHAIN}) endif() # Specify include paths if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME STREQUAL "armel") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) endif() if(TARGET_ARCH_NAME STREQUAL "arm64") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/aarch64-tizen-linux-gnu) endif() endif() if("$ENV{__DistroRid}" MATCHES "android.*") if(TARGET_ARCH_NAME STREQUAL "arm") set(ANDROID_ABI armeabi-v7a) elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(ANDROID_ABI arm64-v8a) endif() # extract platform number required by the NDK's toolchain string(REGEX REPLACE ".*\\.([0-9]+)-.*" "\\1" ANDROID_PLATFORM "$ENV{__DistroRid}") set(ANDROID_TOOLCHAIN clang) set(FEATURE_EVENT_TRACE 0) # disable event trace as there is no lttng-ust package in termux repository set(CMAKE_SYSTEM_LIBRARY_PATH "${CROSS_ROOTFS}/usr/lib") set(CMAKE_SYSTEM_INCLUDE_PATH "${CROSS_ROOTFS}/usr/include") # include official NDK toolchain script include(${CROSS_ROOTFS}/../build/cmake/android.toolchain.cmake) elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") # we cross-compile by instructing clang set(CMAKE_C_COMPILER_TARGET ${triple}) set(CMAKE_CXX_COMPILER_TARGET ${triple}) set(CMAKE_ASM_COMPILER_TARGET ${triple}) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") elseif(ILLUMOS) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") include_directories(SYSTEM ${CROSS_ROOTFS}/include) set(TOOLSET_PREFIX ${TOOLCHAIN}-) function(locate_toolchain_exec exec var) string(TOUPPER ${exec} EXEC_UPPERCASE) if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) return() endif() find_program(EXEC_LOCATION_${exec} NAMES "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" "${TOOLSET_PREFIX}${exec}") if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") endif() set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endfunction() set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") else() set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_ASM_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") endif() # Specify link flags function(add_toolchain_linker_flag Flag) set(Config "${ARGV1}") set(CONFIG_SUFFIX "") if (NOT Config STREQUAL "") set(CONFIG_SUFFIX "_${Config}") endif() set("CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) set("CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) endfunction() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib/${TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}") endif() if(TARGET_ARCH_NAME STREQUAL "armel") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_toolchain_linker_flag(-m32) elseif(ILLUMOS) add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib/amd64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/amd64/lib") endif() # Specify compile options if((TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64|s390x)$" AND NOT "$ENV{__DistroRid}" MATCHES "android.*") OR ILLUMOS) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) endif() if(TARGET_ARCH_NAME MATCHES "^(arm|armel)$") add_compile_options(-mthumb) if (NOT DEFINED CLR_ARM_FPU_TYPE) set (CLR_ARM_FPU_TYPE vfpv3) endif (NOT DEFINED CLR_ARM_FPU_TYPE) add_compile_options (-mfpu=${CLR_ARM_FPU_TYPE}) if (NOT DEFINED CLR_ARM_FPU_CAPABILITY) set (CLR_ARM_FPU_CAPABILITY 0x7) endif (NOT DEFINED CLR_ARM_FPU_CAPABILITY) add_definitions (-DCLR_ARM_FPU_CAPABILITY=${CLR_ARM_FPU_CAPABILITY}) if(TARGET_ARCH_NAME STREQUAL "armel") add_compile_options(-mfloat-abi=softfp) endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_compile_options(-m32) add_compile_options(-Wno-error=unused-command-line-argument) endif() if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME MATCHES "^(armel|arm64)$") add_compile_options(-Wno-deprecated-declarations) # compile-time option add_compile_options(-D__extern_always_inline=inline) # compile-time option endif() endif() # Set LLDB include and library paths for builds that need lldb. if(TARGET_ARCH_NAME MATCHES "^(arm|armel|x86)$") if(TARGET_ARCH_NAME STREQUAL "x86") set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") else() # arm/armel case set(LLVM_CROSS_DIR "$ENV{LLVM_ARM_HOME}") endif() if(LLVM_CROSS_DIR) set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") else() if(TARGET_ARCH_NAME STREQUAL "x86") set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") else() set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") endif() else() # arm/armel case set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") endif() endif() endif() set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) if(EXISTS ${CROSS_ROOTFS}/bin/freebsd-version) set(CMAKE_SYSTEM_NAME FreeBSD) elseif(EXISTS ${CROSS_ROOTFS}/usr/platform/i86pc) set(CMAKE_SYSTEM_NAME SunOS) set(ILLUMOS 1) else() set(CMAKE_SYSTEM_NAME Linux) endif() set(CMAKE_SYSTEM_VERSION 1) if(TARGET_ARCH_NAME STREQUAL "armel") set(CMAKE_SYSTEM_PROCESSOR armv7l) set(TOOLCHAIN "arm-linux-gnueabi") if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm") set(CMAKE_SYSTEM_PROCESSOR armv7l) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv7-alpine-linux-musleabihf) set(TOOLCHAIN "armv7-alpine-linux-musleabihf") elseif(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) set(TOOLCHAIN "armv6-alpine-linux-musleabihf") else() set(TOOLCHAIN "arm-linux-gnueabihf") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(CMAKE_SYSTEM_PROCESSOR aarch64) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) set(TOOLCHAIN "aarch64-alpine-linux-musl") else() set(TOOLCHAIN "aarch64-linux-gnu") endif() if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "aarch64-tizen-linux-gnu/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "s390x") set(CMAKE_SYSTEM_PROCESSOR s390x) set(TOOLCHAIN "s390x-linux-gnu") elseif(TARGET_ARCH_NAME STREQUAL "x86") set(CMAKE_SYSTEM_PROCESSOR i686) set(TOOLCHAIN "i686-linux-gnu") elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(triple "x86_64-unknown-freebsd11") elseif (ILLUMOS) set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(TOOLCHAIN "x86_64-illumos") else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) set(TOOLCHAIN $ENV{TOOLCHAIN}) endif() # Specify include paths if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME STREQUAL "armel") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) endif() if(TARGET_ARCH_NAME STREQUAL "arm64") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/aarch64-tizen-linux-gnu) endif() endif() if("$ENV{__DistroRid}" MATCHES "android.*") if(TARGET_ARCH_NAME STREQUAL "arm") set(ANDROID_ABI armeabi-v7a) elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(ANDROID_ABI arm64-v8a) endif() # extract platform number required by the NDK's toolchain string(REGEX REPLACE ".*\\.([0-9]+)-.*" "\\1" ANDROID_PLATFORM "$ENV{__DistroRid}") set(ANDROID_TOOLCHAIN clang) set(FEATURE_EVENT_TRACE 0) # disable event trace as there is no lttng-ust package in termux repository set(CMAKE_SYSTEM_LIBRARY_PATH "${CROSS_ROOTFS}/usr/lib") set(CMAKE_SYSTEM_INCLUDE_PATH "${CROSS_ROOTFS}/usr/include") # include official NDK toolchain script include(${CROSS_ROOTFS}/../build/cmake/android.toolchain.cmake) elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") # we cross-compile by instructing clang set(CMAKE_C_COMPILER_TARGET ${triple}) set(CMAKE_CXX_COMPILER_TARGET ${triple}) set(CMAKE_ASM_COMPILER_TARGET ${triple}) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") elseif(ILLUMOS) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") include_directories(SYSTEM ${CROSS_ROOTFS}/include) set(TOOLSET_PREFIX ${TOOLCHAIN}-) function(locate_toolchain_exec exec var) string(TOUPPER ${exec} EXEC_UPPERCASE) if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) return() endif() find_program(EXEC_LOCATION_${exec} NAMES "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" "${TOOLSET_PREFIX}${exec}") if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") endif() set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endfunction() set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") else() set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_ASM_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") endif() # Specify link flags function(add_toolchain_linker_flag Flag) set(Config "${ARGV1}") set(CONFIG_SUFFIX "") if (NOT Config STREQUAL "") set(CONFIG_SUFFIX "_${Config}") endif() set("CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) set("CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) endfunction() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib/${TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}") endif() if(TARGET_ARCH_NAME STREQUAL "armel") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_toolchain_linker_flag(-m32) elseif(ILLUMOS) add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib/amd64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/amd64/lib") endif() # Specify compile options if((TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64|s390x)$" AND NOT "$ENV{__DistroRid}" MATCHES "android.*") OR ILLUMOS) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) endif() if(TARGET_ARCH_NAME MATCHES "^(arm|armel)$") add_compile_options(-mthumb) if (NOT DEFINED CLR_ARM_FPU_TYPE) set (CLR_ARM_FPU_TYPE vfpv3) endif (NOT DEFINED CLR_ARM_FPU_TYPE) add_compile_options (-mfpu=${CLR_ARM_FPU_TYPE}) if (NOT DEFINED CLR_ARM_FPU_CAPABILITY) set (CLR_ARM_FPU_CAPABILITY 0x7) endif (NOT DEFINED CLR_ARM_FPU_CAPABILITY) add_definitions (-DCLR_ARM_FPU_CAPABILITY=${CLR_ARM_FPU_CAPABILITY}) if(TARGET_ARCH_NAME STREQUAL "armel") add_compile_options(-mfloat-abi=softfp) endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_compile_options(-m32) add_compile_options(-Wno-error=unused-command-line-argument) endif() if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME MATCHES "^(armel|arm64)$") add_compile_options(-Wno-deprecated-declarations) # compile-time option add_compile_options(-D__extern_always_inline=inline) # compile-time option endif() endif() # Set LLDB include and library paths for builds that need lldb. if(TARGET_ARCH_NAME MATCHES "^(arm|armel|x86)$") if(TARGET_ARCH_NAME STREQUAL "x86") set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") else() # arm/armel case set(LLVM_CROSS_DIR "$ENV{LLVM_ARM_HOME}") endif() if(LLVM_CROSS_DIR) set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") else() if(TARGET_ARCH_NAME STREQUAL "x86") set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") else() set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") endif() else() # arm/armel case set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") endif() endif() endif() set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal class SplitCommentOptions { public static PerLanguageOption2<bool> Enabled = new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments")); } [ExportOptionProvider, Shared] internal class SplitCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SplitCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SplitCommentOptions.Enabled); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal class SplitCommentOptions { public static PerLanguageOption2<bool> Enabled = new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments")); } [ExportOptionProvider, Shared] internal class SplitCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SplitCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SplitCommentOptions.Enabled); } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Features/Core/Portable/ConvertTupleToStruct/Scope.cs
// Licensed to the .NET Foundation under one or more 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.ConvertTupleToStruct { internal enum Scope { ContainingMember, ContainingType, ContainingProject, DependentProjects } }
// Licensed to the .NET Foundation under one or more 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.ConvertTupleToStruct { internal enum Scope { ContainingMember, ContainingType, ContainingProject, DependentProjects } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/Features/Core/Portable/Workspace/ProjectCacheService.SimpleMRUCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Host { internal partial class ProjectCacheService : IProjectCacheHostService { private class SimpleMRUCache { private const int CacheSize = 3; private readonly Node[] _nodes = new Node[CacheSize]; public bool IsEmpty { get { for (var i = 0; i < _nodes.Length; i++) { if (_nodes[i].Data != null) { return false; } } return true; } } public void Touch(object instance) { var oldIndex = -1; var oldTime = DateTime.MaxValue; for (var i = 0; i < _nodes.Length; i++) { if (instance == _nodes[i].Data) { _nodes[i].LastTouched = DateTime.UtcNow; return; } if (oldTime >= _nodes[i].LastTouched) { oldTime = _nodes[i].LastTouched; oldIndex = i; } } Debug.Assert(oldIndex >= 0); _nodes[oldIndex] = new Node(instance, DateTime.UtcNow); } public void ClearExpiredItems(DateTime expirationTime) { for (var i = 0; i < _nodes.Length; i++) { if (_nodes[i].Data != null && _nodes[i].LastTouched < expirationTime) { _nodes[i] = default; } } } public void Clear() => Array.Clear(_nodes, 0, _nodes.Length); private struct Node { public readonly object Data; public DateTime LastTouched; public Node(object data, DateTime lastTouched) { Data = data; LastTouched = lastTouched; } } } private class ImplicitCacheMonitor : IdleProcessor { private readonly ProjectCacheService _owner; private readonly SemaphoreSlim _gate; public ImplicitCacheMonitor(ProjectCacheService owner, TimeSpan backOffTimeSpan) : base(AsynchronousOperationListenerProvider.NullListener, backOffTimeSpan, CancellationToken.None) { _owner = owner; _gate = new SemaphoreSlim(0); Start(); } protected override Task ExecuteAsync() { _owner.ClearExpiredImplicitCache(DateTime.UtcNow - BackOffTimeSpan); return Task.CompletedTask; } public void Touch() { UpdateLastAccessTime(); if (_gate.CurrentCount == 0) { _gate.Release(); } } protected override Task WaitAsync(CancellationToken cancellationToken) { if (_owner.IsImplicitCacheEmpty) { return _gate.WaitAsync(cancellationToken); } return Task.CompletedTask; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Host { internal partial class ProjectCacheService : IProjectCacheHostService { private class SimpleMRUCache { private const int CacheSize = 3; private readonly Node[] _nodes = new Node[CacheSize]; public bool IsEmpty { get { for (var i = 0; i < _nodes.Length; i++) { if (_nodes[i].Data != null) { return false; } } return true; } } public void Touch(object instance) { var oldIndex = -1; var oldTime = DateTime.MaxValue; for (var i = 0; i < _nodes.Length; i++) { if (instance == _nodes[i].Data) { _nodes[i].LastTouched = DateTime.UtcNow; return; } if (oldTime >= _nodes[i].LastTouched) { oldTime = _nodes[i].LastTouched; oldIndex = i; } } Debug.Assert(oldIndex >= 0); _nodes[oldIndex] = new Node(instance, DateTime.UtcNow); } public void ClearExpiredItems(DateTime expirationTime) { for (var i = 0; i < _nodes.Length; i++) { if (_nodes[i].Data != null && _nodes[i].LastTouched < expirationTime) { _nodes[i] = default; } } } public void Clear() => Array.Clear(_nodes, 0, _nodes.Length); private struct Node { public readonly object Data; public DateTime LastTouched; public Node(object data, DateTime lastTouched) { Data = data; LastTouched = lastTouched; } } } private class ImplicitCacheMonitor : IdleProcessor { private readonly ProjectCacheService _owner; private readonly SemaphoreSlim _gate; public ImplicitCacheMonitor(ProjectCacheService owner, TimeSpan backOffTimeSpan) : base(AsynchronousOperationListenerProvider.NullListener, backOffTimeSpan, CancellationToken.None) { _owner = owner; _gate = new SemaphoreSlim(0); Start(); } protected override Task ExecuteAsync() { _owner.ClearExpiredImplicitCache(DateTime.UtcNow - BackOffTimeSpan); return Task.CompletedTask; } public void Touch() { UpdateLastAccessTime(); if (_gate.CurrentCount == 0) { _gate.Release(); } } protected override Task WaitAsync(CancellationToken cancellationToken) { if (_owner.IsImplicitCacheEmpty) { return _gate.WaitAsync(cancellationToken); } return Task.CompletedTask; } } } }
-1
dotnet/roslyn
55,617
Fix regression with conversion to FormattableString
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
jcouv
2021-08-14T01:15:14Z
2021-08-16T19:34:55Z
3ba65c60e7c3227bac1555334e23ca3818673d94
f29a9e1fb4dbcd4845a6fdd5f7649059f9cad89e
Fix regression with conversion to FormattableString. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647 Relates to interpolated string improvements: https://github.com/dotnet/roslyn/issues/51499 (test plan)
./src/EditorFeatures/Core.Wpf/QuickInfo/ProjectionBufferContent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { /// <summary> /// Creates quick info content out of the span of an existing snapshot. The span will be /// used to create a projection buffer out that will then be displayed in the quick info /// window. /// </summary> internal class ProjectionBufferContent : ForegroundThreadAffinitizedObject { private readonly ImmutableArray<SnapshotSpan> _spans; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly IContentType _contentType; private readonly ITextViewRoleSet _roleSet; private ProjectionBufferContent( IThreadingContext threadingContext, ImmutableArray<SnapshotSpan> spans, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentType contentType = null, ITextViewRoleSet roleSet = null) : base(threadingContext) { _spans = spans; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _textEditorFactoryService = textEditorFactoryService; _contentType = contentType; _roleSet = roleSet ?? _textEditorFactoryService.NoRoles; } public static ViewHostingControl Create( IThreadingContext threadingContext, ImmutableArray<SnapshotSpan> spans, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentType contentType = null, ITextViewRoleSet roleSet = null) { var content = new ProjectionBufferContent( threadingContext, spans, projectionBufferFactoryService, editorOptionsFactoryService, textEditorFactoryService, contentType, roleSet); return content.Create(); } private ViewHostingControl Create() { AssertIsForeground(); return new ViewHostingControl(CreateView, CreateBuffer); } private IWpfTextView CreateView(ITextBuffer buffer) { var view = _textEditorFactoryService.CreateTextView(buffer, _roleSet); view.SizeToFit(ThreadingContext); view.Background = Brushes.Transparent; // Zoom out a bit to shrink the text. view.ZoomLevel *= 0.75; // turn off highlight current line view.Options.SetOptionValue(DefaultWpfViewOptions.EnableHighlightCurrentLineId, false); return view; } private IProjectionBuffer CreateBuffer() { return _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _editorOptionsFactoryService.GlobalOptions, _contentType, _spans.ToArray()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { /// <summary> /// Creates quick info content out of the span of an existing snapshot. The span will be /// used to create a projection buffer out that will then be displayed in the quick info /// window. /// </summary> internal class ProjectionBufferContent : ForegroundThreadAffinitizedObject { private readonly ImmutableArray<SnapshotSpan> _spans; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly IContentType _contentType; private readonly ITextViewRoleSet _roleSet; private ProjectionBufferContent( IThreadingContext threadingContext, ImmutableArray<SnapshotSpan> spans, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentType contentType = null, ITextViewRoleSet roleSet = null) : base(threadingContext) { _spans = spans; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _textEditorFactoryService = textEditorFactoryService; _contentType = contentType; _roleSet = roleSet ?? _textEditorFactoryService.NoRoles; } public static ViewHostingControl Create( IThreadingContext threadingContext, ImmutableArray<SnapshotSpan> spans, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentType contentType = null, ITextViewRoleSet roleSet = null) { var content = new ProjectionBufferContent( threadingContext, spans, projectionBufferFactoryService, editorOptionsFactoryService, textEditorFactoryService, contentType, roleSet); return content.Create(); } private ViewHostingControl Create() { AssertIsForeground(); return new ViewHostingControl(CreateView, CreateBuffer); } private IWpfTextView CreateView(ITextBuffer buffer) { var view = _textEditorFactoryService.CreateTextView(buffer, _roleSet); view.SizeToFit(ThreadingContext); view.Background = Brushes.Transparent; // Zoom out a bit to shrink the text. view.ZoomLevel *= 0.75; // turn off highlight current line view.Options.SetOptionValue(DefaultWpfViewOptions.EnableHighlightCurrentLineId, false); return view; } private IProjectionBuffer CreateBuffer() { return _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _editorOptionsFactoryService.GlobalOptions, _contentType, _spans.ToArray()); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class CSharpEditAndContinueAnalyzerTests { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; #region Helpers private static void TestSpans(string source, Func<SyntaxNode, bool> hasLabel) { var tree = SyntaxFactory.ParseSyntaxTree(source); foreach (var expected in GetExpectedSpans(source)) { var expectedText = source.Substring(expected.Start, expected.Length); var token = tree.GetRoot().FindToken(expected.Start); var node = token.Parent; while (!hasLabel(node)) { node = node.Parent; } var actual = CSharpEditAndContinueAnalyzer.GetDiagnosticSpan(node, EditKind.Update); var actualText = source.Substring(actual.Start, actual.Length); Assert.True(expected == actual, $"{Environment.NewLine}Expected span: '{expectedText}' {expected}" + $"{Environment.NewLine}Actual span: '{actualText}' {actual}"); } } private static IEnumerable<TextSpan> GetExpectedSpans(string source) { const string StartTag = "/*<span>*/"; const string EndTag = "/*</span>*/"; var i = 0; while (true) { var start = source.IndexOf(StartTag, i, StringComparison.Ordinal); if (start == -1) { break; } start += StartTag.Length; var end = source.IndexOf(EndTag, start + 1, StringComparison.Ordinal); yield return new TextSpan(start, end - start); i = end + 1; } } private static void TestErrorSpansAllKinds(Func<SyntaxKind, bool> hasLabel) { var unhandledKinds = new List<SyntaxKind>(); foreach (var kind in Enum.GetValues(typeof(SyntaxKind)).Cast<SyntaxKind>().Where(hasLabel)) { TextSpan? span; try { span = CSharpEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(kind, null, EditKind.Update); } catch (NullReferenceException) { // expected, we passed null node continue; } // unexpected: if (span == null) { unhandledKinds.Add(kind); } } AssertEx.Equal(Array.Empty<SyntaxKind>(), unhandledKinds); } #endregion [Fact] public void ErrorSpans_TopLevel() { var source = @" /*<span>*/extern alias A;/*</span>*/ /*<span>*/using Z = Goo.Bar;/*</span>*/ [assembly: /*<span>*/A(1,2,3,4)/*</span>*/, /*<span>*/B/*</span>*/] /*<span>*/namespace N.M/*</span>*/ { } [A, B] /*<span>*/struct S<[A]T>/*</span>*/ : B /*<span>*/where T : new, struct/*</span>*/ { } [A, B] /*<span>*/public abstract partial class C/*</span>*/ { } [A, B] /*<span>*/public abstract partial record R/*</span>*/ { } [A, B] /*<span>*/public abstract partial record struct R/*</span>*/ { } /*<span>*/interface I/*</span>*/ : J, K, L { } [A] /*<span>*/enum E1/*</span>*/ { } /*<span>*/enum E2/*</span>*/ : uint { } /*<span>*/public enum E3/*</span>*/ { Q, [A]R = 3 } [A] /*<span>*/public delegate void D1<T>()/*</span>*/ where T : struct; /*<span>*/delegate C<T> D2()/*</span>*/; [Attrib] /*<span>*/public class Z/*</span>*/ { /*<span>*/int f/*</span>*/; [A]/*<span>*/int f = 1/*</span>*/; /*<span>*/public static readonly int f/*</span>*/; /*<span>*/int M1()/*</span>*/ { } [A]/*<span>*/int M2()/*</span>*/ { } [A]/*<span>*/int M3<T1, T2>()/*</span>*/ where T1 : bar where T2 : baz { } [A]/*<span>*/abstract C<T> M4()/*</span>*/; int M5([A]/*<span>*/Z d = 2345/*</span>*/, /*<span>*/ref int x/*</span>*/, /*<span>*/params int[] x/*</span>*/) { return 1; } [A]/*<span>*/event A E1/*</span>*/; [A]/*<span>*/public event A E2/*</span>*/; [A]/*<span>*/public abstract event A E3/*</span>*/ { /*<span>*/add/*</span>*/; /*<span>*/remove/*</span>*/; } [A]/*<span>*/public abstract event A E4/*</span>*/ { [A, B]/*<span>*/add/*</span>*/ { } [A]/*<span>*/internal remove/*</span>*/ { } } [A]/*<span>*/int P/*</span>*/ { get; set; } [A]/*<span>*/internal string P/*</span>*/ { /*<span>*/internal get/*</span>*/ { } [A]/*<span>*/set/*</span>*/ { }} [A]/*<span>*/internal string this[int a, int b]/*</span>*/ { /*<span>*/get/*</span>*/ { } /*<span>*/set/*</span>*/ { } } [A]/*<span>*/string this[[A]int a = 123]/*</span>*/ { get { } set { } } [A]/*<span>*/public static explicit operator int(Z d)/*</span>*/ { return 1; } [A]/*<span>*/operator double(Z d)/*</span>*/ { return 1; } [A]/*<span>*/public static operator +(Z d, int x)/*</span>*/ { return 1; } [A]/*<span>*/operator +(Z d, int x)/*</span>*/ { return 1; } } "; TestSpans(source, node => SyntaxComparer.TopLevel.HasLabel(node)); } [Fact] public void ErrorSpans_StatementLevel_Update() { var source = @" class C { void M() { /*<span>*/{/*</span>*/} /*<span>*/using (expr)/*</span>*/ {} /*<span>*/fixed (int* a = expr)/*</span>*/ {} /*<span>*/lock (expr)/*</span>*/ {} /*<span>*/yield break;/*</span>*/ /*<span>*/yield return 1;/*</span>*/ /*<span>*/try/*</span>*/ {} catch { }; try {} /*<span>*/catch/*</span>*/ { }; try {} /*<span>*/finally/*</span>*/ { }; /*<span>*/if (expr)/*</span>*/ { }; if (expr) { } /*<span>*/else/*</span>*/ { }; /*<span>*/while (expr)/*</span>*/ { }; /*<span>*/do/*</span>*/ {} while (expr); /*<span>*/for (;;)/*</span>*/ { }; /*<span>*/foreach (var a in b)/*</span>*/ { }; /*<span>*/switch (expr)/*</span>*/ { case 1: break; }; switch (expr) { case 1: /*<span>*/goto case 1;/*</span>*/ }; switch (expr) { case 1: /*<span>*/goto case default;/*</span>*/ }; /*<span>*/label/*</span>*/: Goo(); /*<span>*/checked/*</span>*/ { }; /*<span>*/unchecked/*</span>*/ { }; /*<span>*/unsafe/*</span>*/ { }; /*<span>*/return expr;/*</span>*/ /*<span>*/throw expr;/*</span>*/ /*<span>*/break;/*</span>*/ /*<span>*/continue;/*</span>*/ /*<span>*/goto label;/*</span>*/ /*<span>*/expr;/*</span>*/ /*<span>*/int a;/*</span>*/ F(/*<span>*/(x)/*</span>*/ => x); F(/*<span>*/x/*</span>*/ => x); F(/*<span>*/delegate/*</span>*/(x) { }); F(from a in b /*<span>*/select/*</span>*/ a.x); F(from a in b /*<span>*/let/*</span>*/ x = expr select expr); F(from a in b /*<span>*/where/*</span>*/ expr select expr); F(from a in b /*<span>*/join/*</span>*/ c in d on e equals f select g); F(from a in b orderby /*<span>*/a/*</span>*/ select b); F(from a in b orderby a, /*<span>*/b descending/*</span>*/ select b); F(from a in b /*<span>*/group/*</span>*/ a by b select d); } } "; // TODO: test // /*<span>*/F($$from a in b from c in d select a.x);/*</span>*/ // /*<span>*/F(from a in b $$from c in d select a.x);/*</span>*/ TestSpans(source, kind => SyntaxComparer.Statement.HasLabel(kind)); } /// <summary> /// Verifies that <see cref="CSharpEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl"/> handles all <see cref="SyntaxKind"/>s. /// </summary> [Fact] public void ErrorSpansAllKinds() { TestErrorSpansAllKinds(kind => SyntaxComparer.Statement.HasLabel(kind)); TestErrorSpansAllKinds(kind => SyntaxComparer.TopLevel.HasLabel(kind)); } [Fact] public async Task AnalyzeDocumentAsync_InsignificantChangesInMethodBody() { var source1 = @" class C { public static void Main() { /* comment */ System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var oldText = await oldDocument.GetTextAsync(); var oldSyntaxRoot = await oldDocument.GetSyntaxRootAsync(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var newDocument = newSolution.GetDocument(documentId); var newText = await newDocument.GetTextAsync(); var newSyntaxRoot = await newDocument.GetSyntaxRootAsync(); var oldStatementSource = "System.Console.WriteLine(1);"; var oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal); var oldStatementTextSpan = new TextSpan(oldStatementPosition, oldStatementSource.Length); var oldStatementSpan = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan); var oldStatementSyntax = oldSyntaxRoot.FindNode(oldStatementTextSpan); var baseActiveStatements = new ActiveStatementsMap( ImmutableDictionary.CreateRange(new[] { KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( new ActiveStatement( ordinal: 0, ActiveStatementFlags.IsLeafFrame, new SourceFileSpan(newDocument.FilePath, oldStatementSpan), instructionId: default))) }), ActiveStatementsMap.Empty.InstructionMap); var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.True(result.HasChanges); var syntaxMap = result.SemanticEdits[0].SyntaxMap; Assert.NotNull(syntaxMap); var newStatementSpan = result.ActiveStatements[0].Span; var newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan); var newStatementSyntax = newSyntaxRoot.FindNode(newStatementTextSpan); var oldStatementSyntaxMapped = syntaxMap(newStatementSyntax); Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_Change() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.True(result.HasChanges); Assert.True(result.HasChangesAndErrors); Assert.True(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source, composition: s_composition); var oldProject = workspace.CurrentSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, oldDocument, ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange2() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_Features_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var experimentalFeatures = new Dictionary<string, string>(); // no experimental features to enable var experimental = TestOptions.Regular.WithFeatures(experimentalFeatures); using var workspace = TestWorkspace.CreateCSharp( source, parseOptions: experimental, compilationOptions: null, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, oldDocument, ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); Assert.True(result.RudeEditErrors.IsEmpty); } [Fact] public async Task AnalyzeDocumentAsync_Features_Change() { // these are all the experimental features currently implemented var experimentalFeatures = Array.Empty<string>(); foreach (var feature in experimentalFeatures) { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); } } "; var featuresToEnable = new Dictionary<string, string>() { { feature, "enabled" } }; var experimental = TestOptions.Regular.WithFeatures(featuresToEnable); using var workspace = TestWorkspace.CreateCSharp( source1, parseOptions: experimental, compilationOptions: null, exportProvider: null); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.True(result.HasChanges); Assert.True(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); Assert.Equal(RudeEditKind.ExperimentalFeaturesEnabled, result.RudeEditErrors.Single().Kind); } } [Fact] public async Task AnalyzeDocumentAsync_SemanticError_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1); Bar(); // semantic error } } "; using var workspace = TestWorkspace.CreateCSharp(source, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, oldDocument, ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); Bar(); // semantic error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); Bar(); // semantic error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.True(result.HasChanges); // no declaration errors (error in method body is only reported when emitting): Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() { var source1 = @" class C { public static void Main(Bar x) { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main(Bar x) { System.Console.WriteLine(2); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); Assert.True(result.HasChanges); // No errors reported: EnC analyzer is resilient against semantic errors. // They will be reported by 1) compiler diagnostic analyzer 2) when emitting delta - if still present. Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_AddingNewFileHavingRudeEdits() { var source1 = @" namespace N { class C { public static void Main() { } } } "; var source2 = @" namespace N { public class D { } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); // fork the solution to introduce a change var oldProject = workspace.CurrentSolution.Projects.Single(); var newDocId = DocumentId.CreateNewId(oldProject.Id); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2)); workspace.TryApplyChanges(newSolution); var newProject = newSolution.Projects.Single(); var changes = newProject.GetChanges(oldProject); Assert.Equal(2, newProject.Documents.Count()); Assert.Equal(0, changes.GetChangedDocuments().Count()); Assert.Equal(1, changes.GetAddedDocuments().Count()); var changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()); var result = new List<DocumentAnalysisResults>(); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); foreach (var changedDocumentId in changedDocuments) { result.Add(await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newProject.GetDocument(changedDocumentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None)); } Assert.True(result.IsSingle()); Assert.Equal(1, result.Single().RudeEditErrors.Count()); Assert.Equal(RudeEditKind.Insert, result.Single().RudeEditErrors.Single().Kind); } [Fact] public async Task AnalyzeDocumentAsync_AddingNewFile() { var source1 = @" namespace N { class C { public static void Main() { } } } "; var source2 = @" class D { } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var newDocId = DocumentId.CreateNewId(oldProject.Id); var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2)); workspace.TryApplyChanges(newSolution); var newProject = newSolution.Projects.Single(); var changes = newProject.GetChanges(oldProject); Assert.Equal(2, newProject.Documents.Count()); Assert.Equal(0, changes.GetChangedDocuments().Count()); Assert.Equal(1, changes.GetAddedDocuments().Count()); var changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()); var result = new List<DocumentAnalysisResults>(); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(); foreach (var changedDocumentId in changedDocuments) { result.Add(await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newProject.GetDocument(changedDocumentId), ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None)); } Assert.True(result.IsSingle()); Assert.Empty(result.Single().RudeEditErrors); } [Theory, CombinatorialData] public async Task AnalyzeDocumentAsync_InternalError(bool outOfMemory) { var source1 = @"class C {}"; var source2 = @"class C { int x; }"; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldProject = workspace.CurrentSolution.Projects.Single(); var documentId = DocumentId.CreateNewId(oldProject.Id); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(documentId, "goo.cs", SourceText.From(source2), filePath: "src.cs"); var newProject = newSolution.Projects.Single(); var newDocument = newProject.GetDocument(documentId); var newSyntaxTree = await newDocument.GetSyntaxTreeAsync().ConfigureAwait(false); workspace.TryApplyChanges(newSolution); var baseActiveStatements = ActiveStatementsMap.Empty; var analyzer = new CSharpEditAndContinueAnalyzer(node => { if (node is CompilationUnitSyntax) { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray<LinePositionSpan>.Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None); var expectedDiagnostic = outOfMemory ? $"ENC0089: {string.Format(FeaturesResources.Modifying_source_file_0_requires_restarting_the_application_because_the_file_is_too_big, "src.cs")}" : // Because the error message that is formatted into this template string includes a stacktrace with newlines, we need to replicate that behavior // here so that any trailing punctuation is removed from the translated template string. $"ENC0080: {string.Format(FeaturesResources.Modifying_source_file_0_requires_restarting_the_application_due_to_internal_error_1, "src.cs", "System.NullReferenceException: NullRef!\n")}".Split('\n').First(); AssertEx.Equal(new[] { expectedDiagnostic }, result.RudeEditErrors.Select(d => d.ToDiagnostic(newSyntaxTree)) .Select(d => $"{d.Id}: {d.GetMessage().Split(new[] { Environment.NewLine }, StringSplitOptions.None).First()}")); } [Fact] public async Task AnalyzeDocumentAsync_NotSupportedByRuntime() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var documentId = oldProject.Documents.Single().Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var newDocument = newSolution.GetDocument(documentId); var analyzer = new CSharpEditAndContinueAnalyzer(); var capabilities = EditAndContinueCapabilities.None; var result = await analyzer.AnalyzeDocumentAsync(oldProject, ActiveStatementsMap.Empty, newDocument, ImmutableArray<LinePositionSpan>.Empty, capabilities, CancellationToken.None); Assert.Equal(RudeEditKind.NotSupportedByRuntime, result.RudeEditErrors.Single().Kind); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class CSharpEditAndContinueAnalyzerTests { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; #region Helpers private static void TestSpans(string source, Func<SyntaxNode, bool> hasLabel) { var tree = SyntaxFactory.ParseSyntaxTree(source); foreach (var expected in GetExpectedSpans(source)) { var expectedText = source.Substring(expected.Start, expected.Length); var token = tree.GetRoot().FindToken(expected.Start); var node = token.Parent; while (!hasLabel(node)) { node = node.Parent; } var actual = CSharpEditAndContinueAnalyzer.GetDiagnosticSpan(node, EditKind.Update); var actualText = source.Substring(actual.Start, actual.Length); Assert.True(expected == actual, $"{Environment.NewLine}Expected span: '{expectedText}' {expected}" + $"{Environment.NewLine}Actual span: '{actualText}' {actual}"); } } private static IEnumerable<TextSpan> GetExpectedSpans(string source) { const string StartTag = "/*<span>*/"; const string EndTag = "/*</span>*/"; var i = 0; while (true) { var start = source.IndexOf(StartTag, i, StringComparison.Ordinal); if (start == -1) { break; } start += StartTag.Length; var end = source.IndexOf(EndTag, start + 1, StringComparison.Ordinal); yield return new TextSpan(start, end - start); i = end + 1; } } private static void TestErrorSpansAllKinds(Func<SyntaxKind, bool> hasLabel) { var unhandledKinds = new List<SyntaxKind>(); foreach (var kind in Enum.GetValues(typeof(SyntaxKind)).Cast<SyntaxKind>().Where(hasLabel)) { TextSpan? span; try { span = CSharpEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(kind, null, EditKind.Update); } catch (NullReferenceException) { // expected, we passed null node continue; } // unexpected: if (span == null) { unhandledKinds.Add(kind); } } AssertEx.Equal(Array.Empty<SyntaxKind>(), unhandledKinds); } private static async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, Document newDocument, ActiveStatementsMap activeStatementMap = null, EditAndContinueCapabilities capabilities = EditAndContinueTestHelpers.Net5RuntimeCapabilities) { var analyzer = new CSharpEditAndContinueAnalyzer(); var baseActiveStatements = AsyncLazy.Create(activeStatementMap ?? ActiveStatementsMap.Empty); var lazyCapabilities = AsyncLazy.Create(capabilities); return await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray<LinePositionSpan>.Empty, lazyCapabilities, CancellationToken.None); } #endregion [Fact] public void ErrorSpans_TopLevel() { var source = @" /*<span>*/extern alias A;/*</span>*/ /*<span>*/using Z = Goo.Bar;/*</span>*/ [assembly: /*<span>*/A(1,2,3,4)/*</span>*/, /*<span>*/B/*</span>*/] /*<span>*/namespace N.M/*</span>*/ { } [A, B] /*<span>*/struct S<[A]T>/*</span>*/ : B /*<span>*/where T : new, struct/*</span>*/ { } [A, B] /*<span>*/public abstract partial class C/*</span>*/ { } [A, B] /*<span>*/public abstract partial record R/*</span>*/ { } [A, B] /*<span>*/public abstract partial record struct R/*</span>*/ { } /*<span>*/interface I/*</span>*/ : J, K, L { } [A] /*<span>*/enum E1/*</span>*/ { } /*<span>*/enum E2/*</span>*/ : uint { } /*<span>*/public enum E3/*</span>*/ { Q, [A]R = 3 } [A] /*<span>*/public delegate void D1<T>()/*</span>*/ where T : struct; /*<span>*/delegate C<T> D2()/*</span>*/; [Attrib] /*<span>*/public class Z/*</span>*/ { /*<span>*/int f/*</span>*/; [A]/*<span>*/int f = 1/*</span>*/; /*<span>*/public static readonly int f/*</span>*/; /*<span>*/int M1()/*</span>*/ { } [A]/*<span>*/int M2()/*</span>*/ { } [A]/*<span>*/int M3<T1, T2>()/*</span>*/ where T1 : bar where T2 : baz { } [A]/*<span>*/abstract C<T> M4()/*</span>*/; int M5([A]/*<span>*/Z d = 2345/*</span>*/, /*<span>*/ref int x/*</span>*/, /*<span>*/params int[] x/*</span>*/) { return 1; } [A]/*<span>*/event A E1/*</span>*/; [A]/*<span>*/public event A E2/*</span>*/; [A]/*<span>*/public abstract event A E3/*</span>*/ { /*<span>*/add/*</span>*/; /*<span>*/remove/*</span>*/; } [A]/*<span>*/public abstract event A E4/*</span>*/ { [A, B]/*<span>*/add/*</span>*/ { } [A]/*<span>*/internal remove/*</span>*/ { } } [A]/*<span>*/int P/*</span>*/ { get; set; } [A]/*<span>*/internal string P/*</span>*/ { /*<span>*/internal get/*</span>*/ { } [A]/*<span>*/set/*</span>*/ { }} [A]/*<span>*/internal string this[int a, int b]/*</span>*/ { /*<span>*/get/*</span>*/ { } /*<span>*/set/*</span>*/ { } } [A]/*<span>*/string this[[A]int a = 123]/*</span>*/ { get { } set { } } [A]/*<span>*/public static explicit operator int(Z d)/*</span>*/ { return 1; } [A]/*<span>*/operator double(Z d)/*</span>*/ { return 1; } [A]/*<span>*/public static operator +(Z d, int x)/*</span>*/ { return 1; } [A]/*<span>*/operator +(Z d, int x)/*</span>*/ { return 1; } } "; TestSpans(source, node => SyntaxComparer.TopLevel.HasLabel(node)); } [Fact] public void ErrorSpans_StatementLevel_Update() { var source = @" class C { void M() { /*<span>*/{/*</span>*/} /*<span>*/using (expr)/*</span>*/ {} /*<span>*/fixed (int* a = expr)/*</span>*/ {} /*<span>*/lock (expr)/*</span>*/ {} /*<span>*/yield break;/*</span>*/ /*<span>*/yield return 1;/*</span>*/ /*<span>*/try/*</span>*/ {} catch { }; try {} /*<span>*/catch/*</span>*/ { }; try {} /*<span>*/finally/*</span>*/ { }; /*<span>*/if (expr)/*</span>*/ { }; if (expr) { } /*<span>*/else/*</span>*/ { }; /*<span>*/while (expr)/*</span>*/ { }; /*<span>*/do/*</span>*/ {} while (expr); /*<span>*/for (;;)/*</span>*/ { }; /*<span>*/foreach (var a in b)/*</span>*/ { }; /*<span>*/switch (expr)/*</span>*/ { case 1: break; }; switch (expr) { case 1: /*<span>*/goto case 1;/*</span>*/ }; switch (expr) { case 1: /*<span>*/goto case default;/*</span>*/ }; /*<span>*/label/*</span>*/: Goo(); /*<span>*/checked/*</span>*/ { }; /*<span>*/unchecked/*</span>*/ { }; /*<span>*/unsafe/*</span>*/ { }; /*<span>*/return expr;/*</span>*/ /*<span>*/throw expr;/*</span>*/ /*<span>*/break;/*</span>*/ /*<span>*/continue;/*</span>*/ /*<span>*/goto label;/*</span>*/ /*<span>*/expr;/*</span>*/ /*<span>*/int a;/*</span>*/ F(/*<span>*/(x)/*</span>*/ => x); F(/*<span>*/x/*</span>*/ => x); F(/*<span>*/delegate/*</span>*/(x) { }); F(from a in b /*<span>*/select/*</span>*/ a.x); F(from a in b /*<span>*/let/*</span>*/ x = expr select expr); F(from a in b /*<span>*/where/*</span>*/ expr select expr); F(from a in b /*<span>*/join/*</span>*/ c in d on e equals f select g); F(from a in b orderby /*<span>*/a/*</span>*/ select b); F(from a in b orderby a, /*<span>*/b descending/*</span>*/ select b); F(from a in b /*<span>*/group/*</span>*/ a by b select d); } } "; // TODO: test // /*<span>*/F($$from a in b from c in d select a.x);/*</span>*/ // /*<span>*/F(from a in b $$from c in d select a.x);/*</span>*/ TestSpans(source, kind => SyntaxComparer.Statement.HasLabel(kind)); } /// <summary> /// Verifies that <see cref="CSharpEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl"/> handles all <see cref="SyntaxKind"/>s. /// </summary> [Fact] public void ErrorSpansAllKinds() { TestErrorSpansAllKinds(kind => SyntaxComparer.Statement.HasLabel(kind)); TestErrorSpansAllKinds(kind => SyntaxComparer.TopLevel.HasLabel(kind)); } [Fact] public async Task AnalyzeDocumentAsync_InsignificantChangesInMethodBody() { var source1 = @" class C { public static void Main() { /* comment */ System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var oldText = await oldDocument.GetTextAsync(); var oldSyntaxRoot = await oldDocument.GetSyntaxRootAsync(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var newDocument = newSolution.GetDocument(documentId); var newText = await newDocument.GetTextAsync(); var newSyntaxRoot = await newDocument.GetSyntaxRootAsync(); var oldStatementSource = "System.Console.WriteLine(1);"; var oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal); var oldStatementTextSpan = new TextSpan(oldStatementPosition, oldStatementSource.Length); var oldStatementSpan = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan); var oldStatementSyntax = oldSyntaxRoot.FindNode(oldStatementTextSpan); var baseActiveStatements = new ActiveStatementsMap( ImmutableDictionary.CreateRange(new[] { KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( new ActiveStatement( ordinal: 0, ActiveStatementFlags.IsLeafFrame, new SourceFileSpan(newDocument.FilePath, oldStatementSpan), instructionId: default))) }), ActiveStatementsMap.Empty.InstructionMap); var result = await AnalyzeDocumentAsync(oldProject, newDocument, baseActiveStatements); Assert.True(result.HasChanges); var syntaxMap = result.SemanticEdits[0].SyntaxMap; Assert.NotNull(syntaxMap); var newStatementSpan = result.ActiveStatements[0].Span; var newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan); var newStatementSyntax = newSyntaxRoot.FindNode(newStatementTextSpan); var oldStatementSyntaxMapped = syntaxMap(newStatementSyntax); Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_Change() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var result = await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)); Assert.True(result.HasChanges); Assert.True(result.HasChangesAndErrors); Assert.True(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source, composition: s_composition); var oldProject = workspace.CurrentSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var result = await AnalyzeDocumentAsync(oldProject, oldDocument); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_SyntaxError_NoChange2() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(1) // syntax error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var result = await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_Features_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var experimentalFeatures = new Dictionary<string, string>(); // no experimental features to enable var experimental = TestOptions.Regular.WithFeatures(experimentalFeatures); using var workspace = TestWorkspace.CreateCSharp( source, parseOptions: experimental, compilationOptions: null, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var result = await AnalyzeDocumentAsync(oldProject, oldDocument); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); Assert.True(result.RudeEditErrors.IsEmpty); } [Fact] public async Task AnalyzeDocumentAsync_Features_Change() { // these are all the experimental features currently implemented var experimentalFeatures = Array.Empty<string>(); foreach (var feature in experimentalFeatures) { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); } } "; var featuresToEnable = new Dictionary<string, string>() { { feature, "enabled" } }; var experimental = TestOptions.Regular.WithFeatures(featuresToEnable); using var workspace = TestWorkspace.CreateCSharp( source1, parseOptions: experimental, compilationOptions: null, exportProvider: null); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var result = await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)); Assert.True(result.HasChanges); Assert.True(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); Assert.Equal(RudeEditKind.ExperimentalFeaturesEnabled, result.RudeEditErrors.Single().Kind); } } [Fact] public async Task AnalyzeDocumentAsync_SemanticError_NoChange() { var source = @" class C { public static void Main() { System.Console.WriteLine(1); Bar(); // semantic error } } "; using var workspace = TestWorkspace.CreateCSharp(source, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var result = await AnalyzeDocumentAsync(oldProject, oldDocument); Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); Bar(); // semantic error } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); Bar(); // semantic error } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var result = await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)); Assert.True(result.HasChanges); // no declaration errors (error in method body is only reported when emitting): Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")] public async Task AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() { var source1 = @" class C { public static void Main(Bar x) { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main(Bar x) { System.Console.WriteLine(2); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var oldDocument = oldProject.Documents.Single(); var documentId = oldDocument.Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var result = await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)); Assert.True(result.HasChanges); // No errors reported: EnC analyzer is resilient against semantic errors. // They will be reported by 1) compiler diagnostic analyzer 2) when emitting delta - if still present. Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndSyntaxErrors); } [Fact] public async Task AnalyzeDocumentAsync_AddingNewFileHavingRudeEdits() { var source1 = @" namespace N { class C { public static void Main() { } } } "; var source2 = @" namespace N { public class D { } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); // fork the solution to introduce a change var oldProject = workspace.CurrentSolution.Projects.Single(); var newDocId = DocumentId.CreateNewId(oldProject.Id); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2)); workspace.TryApplyChanges(newSolution); var newProject = newSolution.Projects.Single(); var changes = newProject.GetChanges(oldProject); Assert.Equal(2, newProject.Documents.Count()); Assert.Equal(0, changes.GetChangedDocuments().Count()); Assert.Equal(1, changes.GetAddedDocuments().Count()); var changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()); var result = new List<DocumentAnalysisResults>(); foreach (var changedDocumentId in changedDocuments) { result.Add(await AnalyzeDocumentAsync(oldProject, newProject.GetDocument(changedDocumentId))); } Assert.True(result.IsSingle()); Assert.Equal(1, result.Single().RudeEditErrors.Count()); Assert.Equal(RudeEditKind.Insert, result.Single().RudeEditErrors.Single().Kind); } [Fact] public async Task AnalyzeDocumentAsync_AddingNewFile() { var source1 = @" namespace N { class C { public static void Main() { } } } "; var source2 = @" class D { } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var newDocId = DocumentId.CreateNewId(oldProject.Id); var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2)); workspace.TryApplyChanges(newSolution); var newProject = newSolution.Projects.Single(); var changes = newProject.GetChanges(oldProject); Assert.Equal(2, newProject.Documents.Count()); Assert.Equal(0, changes.GetChangedDocuments().Count()); Assert.Equal(1, changes.GetAddedDocuments().Count()); var changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()); var result = new List<DocumentAnalysisResults>(); foreach (var changedDocumentId in changedDocuments) { result.Add(await AnalyzeDocumentAsync(oldProject, newProject.GetDocument(changedDocumentId))); } Assert.True(result.IsSingle()); Assert.Empty(result.Single().RudeEditErrors); } [Theory, CombinatorialData] public async Task AnalyzeDocumentAsync_InternalError(bool outOfMemory) { var source1 = @"class C {}"; var source2 = @"class C { int x; }"; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldProject = workspace.CurrentSolution.Projects.Single(); var documentId = DocumentId.CreateNewId(oldProject.Id); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(documentId, "goo.cs", SourceText.From(source2), filePath: "src.cs"); var newProject = newSolution.Projects.Single(); var newDocument = newProject.GetDocument(documentId); var newSyntaxTree = await newDocument.GetSyntaxTreeAsync().ConfigureAwait(false); workspace.TryApplyChanges(newSolution); var baseActiveStatements = AsyncLazy.Create(ActiveStatementsMap.Empty); var capabilities = AsyncLazy.Create(EditAndContinueTestHelpers.Net5RuntimeCapabilities); var analyzer = new CSharpEditAndContinueAnalyzer(node => { if (node is CompilationUnitSyntax) { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray<LinePositionSpan>.Empty, capabilities, CancellationToken.None); var expectedDiagnostic = outOfMemory ? $"ENC0089: {string.Format(FeaturesResources.Modifying_source_file_0_requires_restarting_the_application_because_the_file_is_too_big, "src.cs")}" : // Because the error message that is formatted into this template string includes a stacktrace with newlines, we need to replicate that behavior // here so that any trailing punctuation is removed from the translated template string. $"ENC0080: {string.Format(FeaturesResources.Modifying_source_file_0_requires_restarting_the_application_due_to_internal_error_1, "src.cs", "System.NullReferenceException: NullRef!\n")}".Split('\n').First(); AssertEx.Equal(new[] { expectedDiagnostic }, result.RudeEditErrors.Select(d => d.ToDiagnostic(newSyntaxTree)) .Select(d => $"{d.Id}: {d.GetMessage().Split(new[] { Environment.NewLine }, StringSplitOptions.None).First()}")); } [Fact] public async Task AnalyzeDocumentAsync_NotSupportedByRuntime() { var source1 = @" class C { public static void Main() { System.Console.WriteLine(1); } } "; var source2 = @" class C { public static void Main() { System.Console.WriteLine(2); } } "; using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition); var oldSolution = workspace.CurrentSolution; var oldProject = oldSolution.Projects.Single(); var documentId = oldProject.Documents.Single().Id; var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)); var newDocument = newSolution.GetDocument(documentId); var result = await AnalyzeDocumentAsync(oldProject, newDocument, capabilities: EditAndContinueCapabilities.None); Assert.Equal(RudeEditKind.NotSupportedByRuntime, result.RudeEditErrors.Single().Kind); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateEntered(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateEntered(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, EditAndContinueTestHelpers.Net5RuntimeCapabilities, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.GetTestAccessor().SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); debuggingSession.RestartEditSession(inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements, }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.RestartEditSession(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.EditAndContinue.AbstractEditAndContinueAnalyzer; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public static readonly EditAndContinueCapabilities BaselineCapabilities = EditAndContinueCapabilities.Baseline; public static readonly EditAndContinueCapabilities Net5RuntimeCapabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition; public static readonly EditAndContinueCapabilities Net6RuntimeCapabilities = Net5RuntimeCapabilities | EditAndContinueCapabilities.ChangeCustomAttributes | EditAndContinueCapabilities.UpdateParameters; public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); public abstract string LanguageName { get; } public abstract TreeComparer<SyntaxNode> TopSyntaxComparer { get; } private void VerifyDocumentActiveStatementsAndExceptionRegions( ActiveStatementsDescription description, SyntaxTree oldTree, SyntaxTree newTree, ImmutableArray<ActiveStatement> actualNewActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> actualNewExceptionRegions) { // check active statements: AssertSpansEqual(description.NewMappedSpans, actualNewActiveStatements.OrderBy(x => x.Ordinal).Select(s => s.FileSpan), newTree); var oldRoot = oldTree.GetRoot(); // check old exception regions: foreach (var oldStatement in description.OldStatements) { var oldRegions = Analyzer.GetExceptionRegions( oldRoot, oldStatement.UnmappedSpan, isNonLeaf: oldStatement.Statement.IsNonLeaf, CancellationToken.None); AssertSpansEqual(oldStatement.ExceptionRegions.Spans, oldRegions.Spans, oldTree); } // check new exception regions: if (!actualNewExceptionRegions.IsDefault) { Assert.Equal(actualNewActiveStatements.Length, actualNewExceptionRegions.Length); Assert.Equal(description.NewMappedRegions.Length, actualNewExceptionRegions.Length); for (var i = 0; i < actualNewActiveStatements.Length; i++) { var activeStatement = actualNewActiveStatements[i]; AssertSpansEqual(description.NewMappedRegions[activeStatement.Ordinal], actualNewExceptionRegions[i], newTree); } } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, SequencePointUpdates[] expectedLineEdits, SemanticEditDescription[]? expectedSemanticEdits, RudeEditDiagnosticDescription[]? expectedDiagnostics) { VerifySemantics( new[] { editScript }, TargetFramework.NetStandard20, new[] { new DocumentAnalysisResultsDescription(semanticEdits: expectedSemanticEdits, lineEdits: expectedLineEdits, diagnostics: expectedDiagnostics) }, capabilities: Net5RuntimeCapabilities); } internal void VerifySemantics(EditScript<SyntaxNode>[] editScripts, TargetFramework targetFramework, DocumentAnalysisResultsDescription[] expectedResults, EditAndContinueCapabilities? capabilities = null) { Assert.True(editScripts.Length == expectedResults.Length); var documentCount = expectedResults.Length; using var workspace = new AdhocWorkspace(FeaturesTestCompositions.Features.GetHostServices()); CreateProjects(editScripts, workspace, targetFramework, out var oldProject, out var newProject); var oldDocuments = oldProject.Documents.ToArray(); var newDocuments = newProject.Documents.ToArray(); Debug.Assert(oldDocuments.Length == newDocuments.Length); var oldTrees = oldDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var newTrees = newDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var testAccessor = Analyzer.GetTestAccessor(); var allEdits = new List<SemanticEditInfo>(); for (var documentIndex = 0; documentIndex < documentCount; documentIndex++) { var assertMessagePrefix = (documentCount > 0) ? $"Document #{documentIndex}" : null; var expectedResult = expectedResults[documentIndex]; var includeFirstLineInDiagnostics = expectedResult.Diagnostics.Any(d => d.FirstLine != null) == true; var newActiveStatementSpans = expectedResult.ActiveStatements.OldUnmappedTrackingSpans; // we need to rebuild the edit script, so that it operates on nodes associated with the same syntax trees backing the documents: var oldTree = oldTrees[documentIndex]; var newTree = newTrees[documentIndex]; var oldRoot = oldTree.GetRoot(); var newRoot = newTree.GetRoot(); var oldDocument = oldDocuments[documentIndex]; var newDocument = newDocuments[documentIndex]; var oldModel = oldDocument.GetSemanticModelAsync().Result; var newModel = newDocument.GetSemanticModelAsync().Result; Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); var result = Analyzer.AnalyzeDocumentAsync(oldProject, expectedResult.ActiveStatements.OldStatementsMap, newDocument, newActiveStatementSpans, capabilities ?? Net5RuntimeCapabilities, CancellationToken.None).Result; var oldText = oldDocument.GetTextSynchronously(default); var newText = newDocument.GetTextSynchronously(default); VerifyDiagnostics(expectedResult.Diagnostics, result.RudeEditErrors.ToDescription(newText, includeFirstLineInDiagnostics), assertMessagePrefix); if (!expectedResult.SemanticEdits.IsDefault) { if (result.HasChanges) { VerifySemanticEdits(expectedResult.SemanticEdits, result.SemanticEdits, oldModel.Compilation, newModel.Compilation, oldRoot, newRoot, assertMessagePrefix); allEdits.AddRange(result.SemanticEdits); } else { Assert.True(expectedResult.SemanticEdits.IsEmpty); Assert.True(result.SemanticEdits.IsDefault); } } if (!result.HasChanges) { Assert.True(result.ExceptionRegions.IsDefault); Assert.True(result.ActiveStatements.IsDefault); } else { // exception regions not available in presence of rude edits: Assert.Equal(!expectedResult.Diagnostics.IsEmpty, result.ExceptionRegions.IsDefault); VerifyDocumentActiveStatementsAndExceptionRegions( expectedResult.ActiveStatements, oldTree, newTree, result.ActiveStatements, result.ExceptionRegions); } if (!result.RudeEditErrors.IsEmpty) { Assert.True(result.LineEdits.IsDefault); Assert.True(expectedResult.LineEdits.IsDefaultOrEmpty); } else if (!expectedResult.LineEdits.IsDefault) { // check files of line edits: AssertEx.Equal( expectedResult.LineEdits.Select(e => e.FileName), result.LineEdits.Select(e => e.FileName), itemSeparator: ",\r\n", message: "File names of line edits differ in " + assertMessagePrefix); // check lines of line edits: _ = expectedResult.LineEdits.Zip(result.LineEdits, (expected, actual) => { AssertEx.Equal( expected.LineUpdates, actual.LineUpdates, itemSeparator: ",\r\n", itemInspector: s => $"new({s.OldLine}, {s.NewLine})", message: "Line deltas differ in " + assertMessagePrefix); return true; }).ToArray(); } } var duplicateNonPartial = allEdits .Where(e => e.PartialType == null) .GroupBy(e => e.Symbol, SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true)) .Where(g => g.Count() > 1) .Select(g => g.Key); AssertEx.Empty(duplicateNonPartial, "Duplicate non-partial symbols"); // check if we can merge edits without throwing: EditSession.MergePartialEdits(oldProject.GetCompilationAsync().Result!, newProject.GetCompilationAsync().Result!, allEdits, out var _, out var _, CancellationToken.None); } public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnostic> actual, SourceText newSource) => VerifyDiagnostics(expected, actual.ToDescription(newSource, expected.Any(d => d.FirstLine != null))); public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnosticDescription> actual, string? message = null) => AssertEx.SetEqual(expected, actual, message: message, itemSeparator: ",\r\n"); private void VerifySemanticEdits( ImmutableArray<SemanticEditDescription> expectedSemanticEdits, ImmutableArray<SemanticEditInfo> actualSemanticEdits, Compilation oldCompilation, Compilation newCompilation, SyntaxNode oldRoot, SyntaxNode newRoot, string? message = null) { // string comparison to simplify understanding why a test failed: AssertEx.Equal( expectedSemanticEdits.Select(e => $"{e.Kind}: {e.SymbolProvider(newCompilation)}"), actualSemanticEdits.NullToEmpty().Select(e => $"{e.Kind}: {e.Symbol.Resolve(newCompilation).Symbol}"), message: message); for (var i = 0; i < actualSemanticEdits.Length; i++) { var expectedSemanticEdit = expectedSemanticEdits[i]; var actualSemanticEdit = actualSemanticEdits[i]; var editKind = expectedSemanticEdit.Kind; Assert.Equal(editKind, actualSemanticEdit.Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdit.SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdit.SymbolProvider(newCompilation); var symbolKey = actualSemanticEdit.Symbol; if (editKind == SemanticEditKind.Update) { Assert.Equal(expectedOldSymbol, symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true).Symbol); Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else if (editKind is SemanticEditKind.Insert or SemanticEditKind.Replace) { Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else { Assert.False(true, "Only Update, Insert or Replace allowed"); } // Partial types must match: Assert.Equal( expectedSemanticEdit.PartialType?.Invoke(newCompilation), actualSemanticEdit.PartialType?.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); // Edit is expected to have a syntax map: var actualSyntaxMap = actualSemanticEdit.SyntaxMap; Assert.Equal(expectedSemanticEdit.HasSyntaxMap, actualSyntaxMap != null); // If expected map is specified validate its mappings with the actual one: var expectedSyntaxMap = expectedSemanticEdit.SyntaxMap; if (expectedSyntaxMap != null) { Contract.ThrowIfNull(actualSyntaxMap); VerifySyntaxMap(oldRoot, newRoot, expectedSyntaxMap, actualSyntaxMap); } } } private void VerifySyntaxMap( SyntaxNode oldRoot, SyntaxNode newRoot, IEnumerable<KeyValuePair<TextSpan, TextSpan>> expectedSyntaxMap, Func<SyntaxNode, SyntaxNode?> actualSyntaxMap) { foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); } } private void CreateProjects(EditScript<SyntaxNode>[] editScripts, AdhocWorkspace workspace, TargetFramework targetFramework, out Project oldProject, out Project newProject) { oldProject = workspace.AddProject("project", LanguageName).WithMetadataReferences(TargetFrameworkUtil.GetReferences(targetFramework)); var documentIndex = 0; foreach (var editScript in editScripts) { oldProject = oldProject.AddDocument(documentIndex.ToString(), editScript.Match.OldRoot).Project; documentIndex++; } var newSolution = oldProject.Solution; documentIndex = 0; foreach (var oldDocument in oldProject.Documents) { newSolution = newSolution.WithDocumentSyntaxRoot(oldDocument.Id, editScripts[documentIndex].Match.NewRoot, PreservationMode.PreserveIdentity); documentIndex++; } newProject = newSolution.Projects.Single(); } private static void AssertSpansEqual(IEnumerable<SourceFileSpan> expected, IEnumerable<SourceFileSpan> actual, SyntaxTree newTree) { AssertEx.Equal( expected, actual, itemSeparator: "\r\n", itemInspector: span => DisplaySpan(newTree, span)); } private static string DisplaySpan(SyntaxTree tree, SourceFileSpan span) { if (tree.FilePath != span.Path) { return span.ToString(); } var text = tree.GetText(); var code = text.GetSubText(text.Lines.GetTextSpan(span.Span)).ToString().Replace("\r\n", " "); return $"{span}: [{code}]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; var map = analyzer.GetTestAccessor().ComputeMap(bodyMatch, new ArrayBuilder<ActiveNode>(), ref lazyActiveOrMatchedLambdas, new ArrayBuilder<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) => ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) => AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.EditAndContinue.AbstractEditAndContinueAnalyzer; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public const EditAndContinueCapabilities BaselineCapabilities = EditAndContinueCapabilities.Baseline; public const EditAndContinueCapabilities Net5RuntimeCapabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition; public const EditAndContinueCapabilities Net6RuntimeCapabilities = Net5RuntimeCapabilities | EditAndContinueCapabilities.ChangeCustomAttributes | EditAndContinueCapabilities.UpdateParameters; public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); public abstract string LanguageName { get; } public abstract TreeComparer<SyntaxNode> TopSyntaxComparer { get; } private void VerifyDocumentActiveStatementsAndExceptionRegions( ActiveStatementsDescription description, SyntaxTree oldTree, SyntaxTree newTree, ImmutableArray<ActiveStatement> actualNewActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> actualNewExceptionRegions) { // check active statements: AssertSpansEqual(description.NewMappedSpans, actualNewActiveStatements.OrderBy(x => x.Ordinal).Select(s => s.FileSpan), newTree); var oldRoot = oldTree.GetRoot(); // check old exception regions: foreach (var oldStatement in description.OldStatements) { var oldRegions = Analyzer.GetExceptionRegions( oldRoot, oldStatement.UnmappedSpan, isNonLeaf: oldStatement.Statement.IsNonLeaf, CancellationToken.None); AssertSpansEqual(oldStatement.ExceptionRegions.Spans, oldRegions.Spans, oldTree); } // check new exception regions: if (!actualNewExceptionRegions.IsDefault) { Assert.Equal(actualNewActiveStatements.Length, actualNewExceptionRegions.Length); Assert.Equal(description.NewMappedRegions.Length, actualNewExceptionRegions.Length); for (var i = 0; i < actualNewActiveStatements.Length; i++) { var activeStatement = actualNewActiveStatements[i]; AssertSpansEqual(description.NewMappedRegions[activeStatement.Ordinal], actualNewExceptionRegions[i], newTree); } } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, SequencePointUpdates[] expectedLineEdits, SemanticEditDescription[]? expectedSemanticEdits, RudeEditDiagnosticDescription[]? expectedDiagnostics) { VerifySemantics( new[] { editScript }, TargetFramework.NetStandard20, new[] { new DocumentAnalysisResultsDescription(semanticEdits: expectedSemanticEdits, lineEdits: expectedLineEdits, diagnostics: expectedDiagnostics) }, capabilities: Net5RuntimeCapabilities); } internal void VerifySemantics(EditScript<SyntaxNode>[] editScripts, TargetFramework targetFramework, DocumentAnalysisResultsDescription[] expectedResults, EditAndContinueCapabilities? capabilities = null) { Assert.True(editScripts.Length == expectedResults.Length); var documentCount = expectedResults.Length; using var workspace = new AdhocWorkspace(FeaturesTestCompositions.Features.GetHostServices()); CreateProjects(editScripts, workspace, targetFramework, out var oldProject, out var newProject); var oldDocuments = oldProject.Documents.ToArray(); var newDocuments = newProject.Documents.ToArray(); Debug.Assert(oldDocuments.Length == newDocuments.Length); var oldTrees = oldDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var newTrees = newDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var testAccessor = Analyzer.GetTestAccessor(); var allEdits = new List<SemanticEditInfo>(); var lazyCapabilities = AsyncLazy.Create(capabilities ?? Net5RuntimeCapabilities); for (var documentIndex = 0; documentIndex < documentCount; documentIndex++) { var assertMessagePrefix = (documentCount > 0) ? $"Document #{documentIndex}" : null; var expectedResult = expectedResults[documentIndex]; var includeFirstLineInDiagnostics = expectedResult.Diagnostics.Any(d => d.FirstLine != null) == true; var newActiveStatementSpans = expectedResult.ActiveStatements.OldUnmappedTrackingSpans; // we need to rebuild the edit script, so that it operates on nodes associated with the same syntax trees backing the documents: var oldTree = oldTrees[documentIndex]; var newTree = newTrees[documentIndex]; var oldRoot = oldTree.GetRoot(); var newRoot = newTree.GetRoot(); var oldDocument = oldDocuments[documentIndex]; var newDocument = newDocuments[documentIndex]; var oldModel = oldDocument.GetSemanticModelAsync().Result; var newModel = newDocument.GetSemanticModelAsync().Result; Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); var lazyOldActiveStatementMap = AsyncLazy.Create(expectedResult.ActiveStatements.OldStatementsMap); var result = Analyzer.AnalyzeDocumentAsync(oldProject, lazyOldActiveStatementMap, newDocument, newActiveStatementSpans, lazyCapabilities, CancellationToken.None).Result; var oldText = oldDocument.GetTextSynchronously(default); var newText = newDocument.GetTextSynchronously(default); VerifyDiagnostics(expectedResult.Diagnostics, result.RudeEditErrors.ToDescription(newText, includeFirstLineInDiagnostics), assertMessagePrefix); if (!expectedResult.SemanticEdits.IsDefault) { if (result.HasChanges) { VerifySemanticEdits(expectedResult.SemanticEdits, result.SemanticEdits, oldModel.Compilation, newModel.Compilation, oldRoot, newRoot, assertMessagePrefix); allEdits.AddRange(result.SemanticEdits); } else { Assert.True(expectedResult.SemanticEdits.IsEmpty); Assert.True(result.SemanticEdits.IsDefault); } } if (!result.HasChanges) { Assert.True(result.ExceptionRegions.IsDefault); Assert.True(result.ActiveStatements.IsDefault); } else { // exception regions not available in presence of rude edits: Assert.Equal(!expectedResult.Diagnostics.IsEmpty, result.ExceptionRegions.IsDefault); VerifyDocumentActiveStatementsAndExceptionRegions( expectedResult.ActiveStatements, oldTree, newTree, result.ActiveStatements, result.ExceptionRegions); } if (!result.RudeEditErrors.IsEmpty) { Assert.True(result.LineEdits.IsDefault); Assert.True(expectedResult.LineEdits.IsDefaultOrEmpty); } else if (!expectedResult.LineEdits.IsDefault) { // check files of line edits: AssertEx.Equal( expectedResult.LineEdits.Select(e => e.FileName), result.LineEdits.Select(e => e.FileName), itemSeparator: ",\r\n", message: "File names of line edits differ in " + assertMessagePrefix); // check lines of line edits: _ = expectedResult.LineEdits.Zip(result.LineEdits, (expected, actual) => { AssertEx.Equal( expected.LineUpdates, actual.LineUpdates, itemSeparator: ",\r\n", itemInspector: s => $"new({s.OldLine}, {s.NewLine})", message: "Line deltas differ in " + assertMessagePrefix); return true; }).ToArray(); } } var duplicateNonPartial = allEdits .Where(e => e.PartialType == null) .GroupBy(e => e.Symbol, SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true)) .Where(g => g.Count() > 1) .Select(g => g.Key); AssertEx.Empty(duplicateNonPartial, "Duplicate non-partial symbols"); // check if we can merge edits without throwing: EditSession.MergePartialEdits(oldProject.GetCompilationAsync().Result!, newProject.GetCompilationAsync().Result!, allEdits, out var _, out var _, CancellationToken.None); } public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnostic> actual, SourceText newSource) => VerifyDiagnostics(expected, actual.ToDescription(newSource, expected.Any(d => d.FirstLine != null))); public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnosticDescription> actual, string? message = null) => AssertEx.SetEqual(expected, actual, message: message, itemSeparator: ",\r\n"); private void VerifySemanticEdits( ImmutableArray<SemanticEditDescription> expectedSemanticEdits, ImmutableArray<SemanticEditInfo> actualSemanticEdits, Compilation oldCompilation, Compilation newCompilation, SyntaxNode oldRoot, SyntaxNode newRoot, string? message = null) { // string comparison to simplify understanding why a test failed: AssertEx.Equal( expectedSemanticEdits.Select(e => $"{e.Kind}: {e.SymbolProvider(newCompilation)}"), actualSemanticEdits.NullToEmpty().Select(e => $"{e.Kind}: {e.Symbol.Resolve(newCompilation).Symbol}"), message: message); for (var i = 0; i < actualSemanticEdits.Length; i++) { var expectedSemanticEdit = expectedSemanticEdits[i]; var actualSemanticEdit = actualSemanticEdits[i]; var editKind = expectedSemanticEdit.Kind; Assert.Equal(editKind, actualSemanticEdit.Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdit.SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdit.SymbolProvider(newCompilation); var symbolKey = actualSemanticEdit.Symbol; if (editKind == SemanticEditKind.Update) { Assert.Equal(expectedOldSymbol, symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true).Symbol); Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else if (editKind is SemanticEditKind.Insert or SemanticEditKind.Replace) { Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else { Assert.False(true, "Only Update, Insert or Replace allowed"); } // Partial types must match: Assert.Equal( expectedSemanticEdit.PartialType?.Invoke(newCompilation), actualSemanticEdit.PartialType?.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); // Edit is expected to have a syntax map: var actualSyntaxMap = actualSemanticEdit.SyntaxMap; Assert.Equal(expectedSemanticEdit.HasSyntaxMap, actualSyntaxMap != null); // If expected map is specified validate its mappings with the actual one: var expectedSyntaxMap = expectedSemanticEdit.SyntaxMap; if (expectedSyntaxMap != null) { Contract.ThrowIfNull(actualSyntaxMap); VerifySyntaxMap(oldRoot, newRoot, expectedSyntaxMap, actualSyntaxMap); } } } private void VerifySyntaxMap( SyntaxNode oldRoot, SyntaxNode newRoot, IEnumerable<KeyValuePair<TextSpan, TextSpan>> expectedSyntaxMap, Func<SyntaxNode, SyntaxNode?> actualSyntaxMap) { foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); } } private void CreateProjects(EditScript<SyntaxNode>[] editScripts, AdhocWorkspace workspace, TargetFramework targetFramework, out Project oldProject, out Project newProject) { oldProject = workspace.AddProject("project", LanguageName).WithMetadataReferences(TargetFrameworkUtil.GetReferences(targetFramework)); var documentIndex = 0; foreach (var editScript in editScripts) { oldProject = oldProject.AddDocument(documentIndex.ToString(), editScript.Match.OldRoot).Project; documentIndex++; } var newSolution = oldProject.Solution; documentIndex = 0; foreach (var oldDocument in oldProject.Documents) { newSolution = newSolution.WithDocumentSyntaxRoot(oldDocument.Id, editScripts[documentIndex].Match.NewRoot, PreservationMode.PreserveIdentity); documentIndex++; } newProject = newSolution.Projects.Single(); } private static void AssertSpansEqual(IEnumerable<SourceFileSpan> expected, IEnumerable<SourceFileSpan> actual, SyntaxTree newTree) { AssertEx.Equal( expected, actual, itemSeparator: "\r\n", itemInspector: span => DisplaySpan(newTree, span)); } private static string DisplaySpan(SyntaxTree tree, SourceFileSpan span) { if (tree.FilePath != span.Path) { return span.ToString(); } var text = tree.GetText(); var code = text.GetSubText(text.Lines.GetTextSpan(span.Span)).ToString().Replace("\r\n", " "); return $"{span}: [{code}]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; var map = analyzer.GetTestAccessor().ComputeMap(bodyMatch, new ArrayBuilder<ActiveNode>(), ref lazyActiveOrMatchedLambdas, new ArrayBuilder<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) => ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) => AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n"); } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { public Func<Guid, ManagedEditAndContinueAvailability>? IsEditAndContinueAvailable; public Dictionary<Guid, ManagedEditAndContinueAvailability>? LoadedModules; public Func<ImmutableArray<ManagedActiveStatementDebugInfo>>? GetActiveStatementsImpl; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(GetActiveStatementsImpl?.Invoke() ?? ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { if (IsEditAndContinueAvailable != null) { return Task.FromResult(IsEditAndContinueAvailable(mvid)); } if (LoadedModules != null) { return Task.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded)); } throw new NotImplementedException(); } public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); public Task PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) => Task.CompletedTask; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { public Func<Guid, ManagedEditAndContinueAvailability>? IsEditAndContinueAvailable; public Dictionary<Guid, ManagedEditAndContinueAvailability>? LoadedModules; public Func<ImmutableArray<ManagedActiveStatementDebugInfo>>? GetActiveStatementsImpl; public Func<ImmutableArray<string>>? GetCapabilitiesImpl; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(GetActiveStatementsImpl?.Invoke() ?? ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { if (IsEditAndContinueAvailable != null) { return Task.FromResult(IsEditAndContinueAvailable(mvid)); } if (LoadedModules != null) { return Task.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded)); } throw new NotImplementedException(); } public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(GetCapabilitiesImpl?.Invoke() ?? ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); public Task PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) => Task.CompletedTask; } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests <[UseExportProvider]> Public Class VisualBasicEditAndContinueAnalyzerTests Private Shared ReadOnly s_composition As TestComposition = EditorTestCompositions.EditorFeatures #Region "Helpers" Private Shared Sub TestSpans(source As String, hasLabel As Func(Of SyntaxNode, Boolean)) Dim tree = SyntaxFactory.ParseSyntaxTree(ClearSource(source)) For Each expected In GetExpectedPositionsAndSpans(source) Dim expectedSpan = expected.Value Dim expectedText As String = source.Substring(expectedSpan.Start, expectedSpan.Length) Dim node = tree.GetRoot().FindToken(expected.Key).Parent While Not hasLabel(node) node = node.Parent End While Dim actualSpan = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(node.Kind, node, EditKind.Update).Value Dim actualText = source.Substring(actualSpan.Start, actualSpan.Length) Assert.True(expectedSpan = actualSpan, vbCrLf & "Expected span: '" & expectedText & "' " & expectedSpan.ToString() & vbCrLf & "Actual span: '" & actualText & "' " & actualSpan.ToString()) Next End Sub Private Const s_startTag As String = "<span>" Private Const s_endTag As String = "</span>" Private Const s_startSpanMark As String = "[|" Private Const s_endSpanMark As String = "|]" Private Const s_positionMark As Char = "$"c Private Shared Function ClearSource(source As String) As String Return source. Replace(s_startTag, New String(" "c, s_startTag.Length)). Replace(s_endTag, New String(" "c, s_endTag.Length)). Replace(s_startSpanMark, New String(" "c, s_startSpanMark.Length)). Replace(s_endSpanMark, New String(" "c, s_startSpanMark.Length)). Replace(s_positionMark, " "c) End Function Private Shared Iterator Function GetExpectedPositionsAndSpans(source As String) As IEnumerable(Of KeyValuePair(Of Integer, TextSpan)) Dim i As Integer = 0 While True Dim start As Integer = source.IndexOf(s_startTag, i, StringComparison.Ordinal) If start = -1 Then Exit While End If start += s_startTag.Length Dim [end] As Integer = source.IndexOf(s_endTag, start + 1, StringComparison.Ordinal) Dim length = [end] - start Dim position = source.IndexOf(s_positionMark, start, length) Dim span As TextSpan If position < 0 Then position = start span = New TextSpan(start, length) Else position += 1 span = TextSpan.FromBounds(source.IndexOf(s_startSpanMark, start, length, StringComparison.Ordinal) + s_startSpanMark.Length, source.IndexOf(s_endSpanMark, start, length, StringComparison.Ordinal)) End If Yield KeyValuePairUtil.Create(position, span) i = [end] + 1 End While End Function Private Shared Sub TestErrorSpansAllKinds(hasLabel As Func(Of SyntaxKind, Boolean)) Dim unhandledKinds As List(Of SyntaxKind) = New List(Of SyntaxKind)() For Each k In [Enum].GetValues(GetType(SyntaxKind)).Cast(Of SyntaxKind)().Where(hasLabel) Dim span As TextSpan? Try span = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(k, Nothing, EditKind.Update) #Disable Warning IDE0059 ' Unnecessary assignment of a value - https://github.com/dotnet/roslyn/issues/45896 Catch e1 As NullReferenceException #Enable Warning IDE0059 ' Unnecessary assignment of a value ' expected, we passed null node Continue For End Try ' unexpected If span Is Nothing Then unhandledKinds.Add(k) End If Next AssertEx.Equal(Array.Empty(Of SyntaxKind)(), unhandledKinds) End Sub #End Region <Fact> Public Sub ErrorSpans_TopLevel() Dim source = " <span>Option Strict Off</span> <span>Imports Z = Goo.Bar</span> <<span>Assembly: A(1,2,3,4)</span>, <span>B</span>> <span>Namespace N.M</span> End Namespace <A, B> Structure S(Of <span>T</span> As {New, Class, I}) Inherits B End Structure Structure S(Of <span>T</span> As {New, Class, I}) End Structure Structure S(Of <span>T</span> As {New, Class, I}) End Structure <A, B> <span>Public MustInherit Partial Class C</span> End Class <span>Interface I</span> Implements J, K, L End Interface <A> <span>Enum E1</span> End Enum <span>Enum E2</span> As UShort End Enum <span>Public Enum E3</span> Q <A>R = 3 End Enum <A> <span>Public Delegate Sub D1(Of T As Struct)()</span> <span>Delegate Function D2()</span> As C(Of T) <span>Delegate Function D2</span> As C(Of T) <span>Delegate Sub D2</span> As C(Of T) <Attrib> <span>Public MustInherit Class Z</span> <span>Dim f0 As Integer</span> <span>Dim WithEvents EClass As New EventClass</span> <A><span>Dim f1 = 1</span> <A><span>Dim f2 As Integer = 1</span> Private <span>f3()</span>, <span>f4?</span>, <span>f5</span> As Integer, <span>f6</span> As New C() <span>Public Shared ReadOnly f As Integer</span> <A><span>Function M1()</span> As Integer End Function <span>Function M2()</span> As Integer Implements I.Goo End Function <span>Function M3()</span> As Integer Handles I.E End Function <span>Private Function M4(Of S, T)()</span> As Integer Handles I.E End Function <span>MustOverride Function M5</span> Sub M6(<A><span>Optional p1 As Integer = 2131</span>, <span>p2</span> As Integer, <span>p3</span>, <Out><span>ByRef p3</span>, <span>ParamArray x() As Integer</span>) End Sub <A><span>Event E1</span> As A <A><span>Private Event E1</span> As A <A><span>Property P</span> As Integer <A><span>Public MustOverride Custom Event E3</span> As A <A><span>AddHandler(value As Action)</span> End AddHandler <A><span>RemoveHandler(value As Action)</span> End RemoveHandler <A><span>RaiseEvent</span> End RaiseEvent End Event <A><span>Property P</span> As Integer <A><span>Get</span> End Get <A><span>Private Set(value As Integer)</span> End Set End Property <A><span>Public Shared Narrowing Operator CType(d As Z)</span> As Integer End Operator End Class " TestSpans(source, Function(node) SyntaxComparer.TopLevel.HasLabel(node)) End Sub <Fact> Public Sub ErrorSpans_StatementLevel_Update() Dim source = " Class C Sub M() <span>While expr</span> <span>Continue While</span> <span>Exit While</span> End While <span>Do</span> <span>Continue Do</span> <span>Exit Do</span> Loop While expr <span>Do</span> Loop <span>Do Until expr</span> Loop <span>Do While expr</span> Loop <span>For Each a In b</span> <span>Continue For</span> <span>Exit For</span> Next <span>For i = 1 To 10 Step 2</span> Next <span>Using expr</span> End Using <span>SyncLock expr</span> End SyncLock <span>With z</span> <span>.M()</span> End With <span>label:</span> <span>F()</span> <span>Static a As Integer = 1</span> <span>Dim b = 2</span> <span>Const c = 4</span> Dim <span>c</span>, <span>d</span> As New C() <span>GoTo label</span> <span>Stop</span> <span>End</span> <span>Exit Sub</span> <span>Return</span> <span>Return 1</span> <span>Throw</span> <span>Throw expr</span> <span>Try</span> <span>Exit Try</span> <span>Catch</span> End Try <span>Try</span> <span>Catch e As E</span> End Try <span>Try</span> <span>Catch e As E When True</span> End Try <span>Try</span> <span>Finally</span> End Try <span>If expr Then</span> End If <span>If expr</span> <span>ElseIf expr</span> <span>Else</span> End If <span>If True Then</span> M1() <span>Else</span> M2() <span>Select expr</span> <span>Case 1</span> End Select <span>Select expr</span> <span>Case 1</span> <span>GoTo 1</span> End Select <span>Select expr</span> <span>Case 1</span> <span>GoTo label</span> <span>Case 4 To 9</span> <span>Exit Select</span> <span>Case = 2</span> <span>Case < 2</span> <span>Case > 2</span> <span>Case Else</span> <span>Return</span> End Select <span>On Error Resume Next</span> <span>On Error Goto 0</span> <span>On Error Goto -1</span> <span>On Error GoTo label</span> <span>Resume</span> <span>Resume Next</span> <span>AddHandler e, AddressOf M</span> <span>RemoveHandler e, AddressOf M</span> <span>RaiseEvent e()</span> <span>Error 1</span> <span>Mid(a, 1, 2) = """"</span> <span>a = b</span> <span>Call M()</span> <span>Dim intArray(10, 10, 10) As Integer</span> <span>ReDim Preserve intArray(10, 10, 20)</span> <span>ReDim Preserve intArray(10, 10, 15)</span> <span>ReDim intArray(10, 10, 10)</span> <span>Erase intArray</span> F(<span>Function(x)</span> x) F(<span>Sub(x)</span> M()) F(<span>[|Aggregate|] z $In {1, 2, 3}</span> Into <span>Max(z)</span>) F(<span>[|From|] z $In {1, 2, 3}</span>? Order By <span>z Descending</span>, <span>z Ascending</span>, <span>z</span> <span>[|Take While|] z $> 0</span>) F(From z1 In {1, 2, 3} <span>[|Join|] z2 $In {1, 2, 3}</span> On z1 Equals z2 <span>[|Select|] z1 $+ z2</span>) F(From z1 In {1, 2, 3} Join z2 In {1, 2, 3} On <span>$z1 [|Equals|] z2</span> Select z1 + z2) F(From z1 In {1, 2, 3} Join z2 In {1, 2, 3} On <span>z1 [|Equals|] $z2</span> Select z1 + z2) F(From a In b <span>[|Let|] x = $expr</span> Select expr) F(From a In b <span>[|Group|] $a1 By b2 Into z1</span> Select d1) F(From a In b <span>[|Group|] a1 By $b2 Into z2</span> Select d2) F(From a In b Group a1 By b2 Into <span>z3</span> Select d3) F(From cust In A <span>[|Group Join|] ord In $B On z4 Equals y4 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 4)</span> Select 1) F(From cust In A <span>Group Join ord In B On $z5 [|Equals|] y5 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 3)</span> Select 1) F(From cust In A <span>Group Join ord In B On z6 [|Equals|] $y6 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 2)</span> Select 1) F(From cust In A Group Join ord In B On z7 Equals y7 Into CustomerOrders = Group, OrderTotal = <span>Sum(ord.Total + 1)</span> Select 1) End Sub End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) source = " Class C Iterator Function M() As IEnumerable(Of Integer) <span>Yield 1</span> End Function End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) source = " Class C Async Function M() As Task(Of Integer) <span>Await expr</span> End Function End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) End Sub ''' <summary> ''' Verifies that <see cref="VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl"/> handles all <see cref="SyntaxKind"/> s. ''' </summary> <Fact> Public Sub ErrorSpansAllKinds() TestErrorSpansAllKinds(Function(kind) SyntaxComparer.Statement.HasLabel(kind, ignoreVariableDeclarations:=False)) TestErrorSpansAllKinds(Function(kind) SyntaxComparer.TopLevel.HasLabel(kind, ignoreVariableDeclarations:=False)) End Sub <Fact> Public Async Function AnalyzeDocumentAsync_InsignificantChangesInMethodBody() As Task Dim source1 = " Class C Sub Main() System.Console.WriteLine(1) End Sub End Class " Dim source2 = " Class C Sub Main() System.Console.WriteLine(1) End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.First() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim oldText = Await oldDocument.GetTextAsync() Dim oldSyntaxRoot = Await oldDocument.GetSyntaxRootAsync() Dim newDocument = newSolution.GetDocument(documentId) Dim newText = Await newDocument.GetTextAsync() Dim newSyntaxRoot = Await newDocument.GetSyntaxRootAsync() Dim oldStatementSource = "System.Console.WriteLine(1)" Dim oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal) Dim oldStatementTextSpan = New TextSpan(oldStatementPosition, oldStatementSource.Length) Dim oldStatementSpan = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan) Dim oldStatementSyntax = oldSyntaxRoot.FindNode(oldStatementTextSpan) Dim baseActiveStatements = New ActiveStatementsMap( ImmutableDictionary.CreateRange( { KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( New ActiveStatement( ordinal:=0, ActiveStatementFlags.IsLeafFrame, New SourceFileSpan(newDocument.FilePath, oldStatementSpan), instructionId:=Nothing))) }), ActiveStatementsMap.Empty.InstructionMap) Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) Assert.True(result.HasChanges) Dim syntaxMap = result.SemanticEdits(0).SyntaxMap Assert.NotNull(syntaxMap) Dim newStatementSpan = result.ActiveStatements(0).Span Dim newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan) Dim newStatementSyntax = newSyntaxRoot.FindNode(newStatementTextSpan) Dim oldStatementSyntaxMapped = syntaxMap(newStatementSyntax) Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange1() As Task Dim source = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, oldDocument, ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange2() As Task Dim source1 = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Dim source2 = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim oldSolution = workspace.CurrentSolution Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SemanticError_NoChange() As Task Dim source = " Class C Public Shared Sub Main() System.Console.WriteLine(1) Bar() End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, oldDocument, ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")> Public Async Function AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() As Task Dim source1 = " Class C Public Shared Sub Main() System.Console.WriteLine(1) Bar() End Sub End Class " Dim source2 = " Class C Public Shared Sub Main() System.Console.WriteLine(2) Bar() End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim oldSolution = workspace.CurrentSolution Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) ' no declaration errors (error in method body is only reported when emitting) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")> Public Async Function AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() As Task Dim source1 = " Class C Public Shared Sub Main(x As Bar) System.Console.WriteLine(1) End Sub End Class " Dim source2 = " Class C Public Shared Sub Main(x As Bar) System.Console.WriteLine(2) End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.Single() Dim documentId = oldProject.Documents.Single().Id Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim result = Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newSolution.GetDocument(documentId), ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None) Assert.True(result.HasChanges) ' No errors reported: EnC analyzer is resilient against semantic errors. ' They will be reported by 1) compiler diagnostic analyzer 2) when emitting delta - if still present. Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_AddingNewFile() As Task Dim source1 = " Namespace N Class C Public Shared Sub Main() End Sub End Class End Namespace " Dim source2 = " Class D End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.Single() Dim newDocId = DocumentId.CreateNewId(oldProject.Id) Dim newSolution = oldSolution.AddDocument(newDocId, "goo.vb", SourceText.From(source2)) workspace.TryApplyChanges(newSolution) Dim newProject = newSolution.Projects.Single() Dim changes = newProject.GetChanges(oldProject) Assert.Equal(2, newProject.Documents.Count()) Assert.Equal(0, changes.GetChangedDocuments().Count()) Assert.Equal(1, changes.GetAddedDocuments().Count()) Dim changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()) Dim result = New List(Of DocumentAnalysisResults)() Dim baseActiveStatements = ActiveStatementsMap.Empty Dim analyzer = New VisualBasicEditAndContinueAnalyzer() For Each changedDocumentId In changedDocuments result.Add(Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newProject.GetDocument(changedDocumentId), ImmutableArray(Of LinePositionSpan).Empty, EditAndContinueTestHelpers.Net5RuntimeCapabilities, CancellationToken.None)) Next Assert.True(result.IsSingle()) Assert.Empty(result.Single().RudeEditErrors) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests <[UseExportProvider]> Public Class VisualBasicEditAndContinueAnalyzerTests Private Shared ReadOnly s_composition As TestComposition = EditorTestCompositions.EditorFeatures #Region "Helpers" Private Shared Sub TestSpans(source As String, hasLabel As Func(Of SyntaxNode, Boolean)) Dim tree = SyntaxFactory.ParseSyntaxTree(ClearSource(source)) For Each expected In GetExpectedPositionsAndSpans(source) Dim expectedSpan = expected.Value Dim expectedText As String = source.Substring(expectedSpan.Start, expectedSpan.Length) Dim node = tree.GetRoot().FindToken(expected.Key).Parent While Not hasLabel(node) node = node.Parent End While Dim actualSpan = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(node.Kind, node, EditKind.Update).Value Dim actualText = source.Substring(actualSpan.Start, actualSpan.Length) Assert.True(expectedSpan = actualSpan, vbCrLf & "Expected span: '" & expectedText & "' " & expectedSpan.ToString() & vbCrLf & "Actual span: '" & actualText & "' " & actualSpan.ToString()) Next End Sub Private Const s_startTag As String = "<span>" Private Const s_endTag As String = "</span>" Private Const s_startSpanMark As String = "[|" Private Const s_endSpanMark As String = "|]" Private Const s_positionMark As Char = "$"c Private Shared Function ClearSource(source As String) As String Return source. Replace(s_startTag, New String(" "c, s_startTag.Length)). Replace(s_endTag, New String(" "c, s_endTag.Length)). Replace(s_startSpanMark, New String(" "c, s_startSpanMark.Length)). Replace(s_endSpanMark, New String(" "c, s_startSpanMark.Length)). Replace(s_positionMark, " "c) End Function Private Shared Iterator Function GetExpectedPositionsAndSpans(source As String) As IEnumerable(Of KeyValuePair(Of Integer, TextSpan)) Dim i As Integer = 0 While True Dim start As Integer = source.IndexOf(s_startTag, i, StringComparison.Ordinal) If start = -1 Then Exit While End If start += s_startTag.Length Dim [end] As Integer = source.IndexOf(s_endTag, start + 1, StringComparison.Ordinal) Dim length = [end] - start Dim position = source.IndexOf(s_positionMark, start, length) Dim span As TextSpan If position < 0 Then position = start span = New TextSpan(start, length) Else position += 1 span = TextSpan.FromBounds(source.IndexOf(s_startSpanMark, start, length, StringComparison.Ordinal) + s_startSpanMark.Length, source.IndexOf(s_endSpanMark, start, length, StringComparison.Ordinal)) End If Yield KeyValuePairUtil.Create(position, span) i = [end] + 1 End While End Function Private Shared Sub TestErrorSpansAllKinds(hasLabel As Func(Of SyntaxKind, Boolean)) Dim unhandledKinds As List(Of SyntaxKind) = New List(Of SyntaxKind)() For Each k In [Enum].GetValues(GetType(SyntaxKind)).Cast(Of SyntaxKind)().Where(hasLabel) Dim span As TextSpan? Try span = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(k, Nothing, EditKind.Update) #Disable Warning IDE0059 ' Unnecessary assignment of a value - https://github.com/dotnet/roslyn/issues/45896 Catch e1 As NullReferenceException #Enable Warning IDE0059 ' Unnecessary assignment of a value ' expected, we passed null node Continue For End Try ' unexpected If span Is Nothing Then unhandledKinds.Add(k) End If Next AssertEx.Equal(Array.Empty(Of SyntaxKind)(), unhandledKinds) End Sub Private Shared Async Function AnalyzeDocumentAsync(oldProject As Project, newDocument As Document, Optional activeStatementMap As ActiveStatementsMap = Nothing) As Task(Of DocumentAnalysisResults) Dim analyzer = New VisualBasicEditAndContinueAnalyzer() Dim baseActiveStatements = AsyncLazy.Create(If(activeStatementMap, ActiveStatementsMap.Empty)) Dim capabilities = AsyncLazy.Create(EditAndContinueTestHelpers.Net5RuntimeCapabilities) Return Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray(Of LinePositionSpan).Empty, capabilities, CancellationToken.None) End Function #End Region <Fact> Public Sub ErrorSpans_TopLevel() Dim source = " <span>Option Strict Off</span> <span>Imports Z = Goo.Bar</span> <<span>Assembly: A(1,2,3,4)</span>, <span>B</span>> <span>Namespace N.M</span> End Namespace <A, B> Structure S(Of <span>T</span> As {New, Class, I}) Inherits B End Structure Structure S(Of <span>T</span> As {New, Class, I}) End Structure Structure S(Of <span>T</span> As {New, Class, I}) End Structure <A, B> <span>Public MustInherit Partial Class C</span> End Class <span>Interface I</span> Implements J, K, L End Interface <A> <span>Enum E1</span> End Enum <span>Enum E2</span> As UShort End Enum <span>Public Enum E3</span> Q <A>R = 3 End Enum <A> <span>Public Delegate Sub D1(Of T As Struct)()</span> <span>Delegate Function D2()</span> As C(Of T) <span>Delegate Function D2</span> As C(Of T) <span>Delegate Sub D2</span> As C(Of T) <Attrib> <span>Public MustInherit Class Z</span> <span>Dim f0 As Integer</span> <span>Dim WithEvents EClass As New EventClass</span> <A><span>Dim f1 = 1</span> <A><span>Dim f2 As Integer = 1</span> Private <span>f3()</span>, <span>f4?</span>, <span>f5</span> As Integer, <span>f6</span> As New C() <span>Public Shared ReadOnly f As Integer</span> <A><span>Function M1()</span> As Integer End Function <span>Function M2()</span> As Integer Implements I.Goo End Function <span>Function M3()</span> As Integer Handles I.E End Function <span>Private Function M4(Of S, T)()</span> As Integer Handles I.E End Function <span>MustOverride Function M5</span> Sub M6(<A><span>Optional p1 As Integer = 2131</span>, <span>p2</span> As Integer, <span>p3</span>, <Out><span>ByRef p3</span>, <span>ParamArray x() As Integer</span>) End Sub <A><span>Event E1</span> As A <A><span>Private Event E1</span> As A <A><span>Property P</span> As Integer <A><span>Public MustOverride Custom Event E3</span> As A <A><span>AddHandler(value As Action)</span> End AddHandler <A><span>RemoveHandler(value As Action)</span> End RemoveHandler <A><span>RaiseEvent</span> End RaiseEvent End Event <A><span>Property P</span> As Integer <A><span>Get</span> End Get <A><span>Private Set(value As Integer)</span> End Set End Property <A><span>Public Shared Narrowing Operator CType(d As Z)</span> As Integer End Operator End Class " TestSpans(source, Function(node) SyntaxComparer.TopLevel.HasLabel(node)) End Sub <Fact> Public Sub ErrorSpans_StatementLevel_Update() Dim source = " Class C Sub M() <span>While expr</span> <span>Continue While</span> <span>Exit While</span> End While <span>Do</span> <span>Continue Do</span> <span>Exit Do</span> Loop While expr <span>Do</span> Loop <span>Do Until expr</span> Loop <span>Do While expr</span> Loop <span>For Each a In b</span> <span>Continue For</span> <span>Exit For</span> Next <span>For i = 1 To 10 Step 2</span> Next <span>Using expr</span> End Using <span>SyncLock expr</span> End SyncLock <span>With z</span> <span>.M()</span> End With <span>label:</span> <span>F()</span> <span>Static a As Integer = 1</span> <span>Dim b = 2</span> <span>Const c = 4</span> Dim <span>c</span>, <span>d</span> As New C() <span>GoTo label</span> <span>Stop</span> <span>End</span> <span>Exit Sub</span> <span>Return</span> <span>Return 1</span> <span>Throw</span> <span>Throw expr</span> <span>Try</span> <span>Exit Try</span> <span>Catch</span> End Try <span>Try</span> <span>Catch e As E</span> End Try <span>Try</span> <span>Catch e As E When True</span> End Try <span>Try</span> <span>Finally</span> End Try <span>If expr Then</span> End If <span>If expr</span> <span>ElseIf expr</span> <span>Else</span> End If <span>If True Then</span> M1() <span>Else</span> M2() <span>Select expr</span> <span>Case 1</span> End Select <span>Select expr</span> <span>Case 1</span> <span>GoTo 1</span> End Select <span>Select expr</span> <span>Case 1</span> <span>GoTo label</span> <span>Case 4 To 9</span> <span>Exit Select</span> <span>Case = 2</span> <span>Case < 2</span> <span>Case > 2</span> <span>Case Else</span> <span>Return</span> End Select <span>On Error Resume Next</span> <span>On Error Goto 0</span> <span>On Error Goto -1</span> <span>On Error GoTo label</span> <span>Resume</span> <span>Resume Next</span> <span>AddHandler e, AddressOf M</span> <span>RemoveHandler e, AddressOf M</span> <span>RaiseEvent e()</span> <span>Error 1</span> <span>Mid(a, 1, 2) = """"</span> <span>a = b</span> <span>Call M()</span> <span>Dim intArray(10, 10, 10) As Integer</span> <span>ReDim Preserve intArray(10, 10, 20)</span> <span>ReDim Preserve intArray(10, 10, 15)</span> <span>ReDim intArray(10, 10, 10)</span> <span>Erase intArray</span> F(<span>Function(x)</span> x) F(<span>Sub(x)</span> M()) F(<span>[|Aggregate|] z $In {1, 2, 3}</span> Into <span>Max(z)</span>) F(<span>[|From|] z $In {1, 2, 3}</span>? Order By <span>z Descending</span>, <span>z Ascending</span>, <span>z</span> <span>[|Take While|] z $> 0</span>) F(From z1 In {1, 2, 3} <span>[|Join|] z2 $In {1, 2, 3}</span> On z1 Equals z2 <span>[|Select|] z1 $+ z2</span>) F(From z1 In {1, 2, 3} Join z2 In {1, 2, 3} On <span>$z1 [|Equals|] z2</span> Select z1 + z2) F(From z1 In {1, 2, 3} Join z2 In {1, 2, 3} On <span>z1 [|Equals|] $z2</span> Select z1 + z2) F(From a In b <span>[|Let|] x = $expr</span> Select expr) F(From a In b <span>[|Group|] $a1 By b2 Into z1</span> Select d1) F(From a In b <span>[|Group|] a1 By $b2 Into z2</span> Select d2) F(From a In b Group a1 By b2 Into <span>z3</span> Select d3) F(From cust In A <span>[|Group Join|] ord In $B On z4 Equals y4 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 4)</span> Select 1) F(From cust In A <span>Group Join ord In B On $z5 [|Equals|] y5 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 3)</span> Select 1) F(From cust In A <span>Group Join ord In B On z6 [|Equals|] $y6 Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 2)</span> Select 1) F(From cust In A Group Join ord In B On z7 Equals y7 Into CustomerOrders = Group, OrderTotal = <span>Sum(ord.Total + 1)</span> Select 1) End Sub End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) source = " Class C Iterator Function M() As IEnumerable(Of Integer) <span>Yield 1</span> End Function End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) source = " Class C Async Function M() As Task(Of Integer) <span>Await expr</span> End Function End Class " TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel) End Sub ''' <summary> ''' Verifies that <see cref="VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl"/> handles all <see cref="SyntaxKind"/> s. ''' </summary> <Fact> Public Sub ErrorSpansAllKinds() TestErrorSpansAllKinds(Function(kind) SyntaxComparer.Statement.HasLabel(kind, ignoreVariableDeclarations:=False)) TestErrorSpansAllKinds(Function(kind) SyntaxComparer.TopLevel.HasLabel(kind, ignoreVariableDeclarations:=False)) End Sub <Fact> Public Async Function AnalyzeDocumentAsync_InsignificantChangesInMethodBody() As Task Dim source1 = " Class C Sub Main() System.Console.WriteLine(1) End Sub End Class " Dim source2 = " Class C Sub Main() System.Console.WriteLine(1) End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.First() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim oldText = Await oldDocument.GetTextAsync() Dim oldSyntaxRoot = Await oldDocument.GetSyntaxRootAsync() Dim newDocument = newSolution.GetDocument(documentId) Dim newText = Await newDocument.GetTextAsync() Dim newSyntaxRoot = Await newDocument.GetSyntaxRootAsync() Dim oldStatementSource = "System.Console.WriteLine(1)" Dim oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal) Dim oldStatementTextSpan = New TextSpan(oldStatementPosition, oldStatementSource.Length) Dim oldStatementSpan = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan) Dim oldStatementSyntax = oldSyntaxRoot.FindNode(oldStatementTextSpan) Dim baseActiveStatements = New ActiveStatementsMap( ImmutableDictionary.CreateRange( { KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create( New ActiveStatement( ordinal:=0, ActiveStatementFlags.IsLeafFrame, New SourceFileSpan(newDocument.FilePath, oldStatementSpan), instructionId:=Nothing))) }), ActiveStatementsMap.Empty.InstructionMap) Dim result = Await AnalyzeDocumentAsync(oldProject, newDocument, baseActiveStatements) Assert.True(result.HasChanges) Dim syntaxMap = result.SemanticEdits(0).SyntaxMap Assert.NotNull(syntaxMap) Dim newStatementSpan = result.ActiveStatements(0).Span Dim newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan) Dim newStatementSyntax = newSyntaxRoot.FindNode(newStatementTextSpan) Dim oldStatementSyntaxMapped = syntaxMap(newStatementSyntax) Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange1() As Task Dim source = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim result = Await AnalyzeDocumentAsync(oldProject, oldDocument) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange2() As Task Dim source1 = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Dim source2 = " Class C Public Shared Sub Main() System.Console.WriteLine(1 ' syntax error End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim oldSolution = workspace.CurrentSolution Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_SemanticError_NoChange() As Task Dim source = " Class C Public Shared Sub Main() System.Console.WriteLine(1) Bar() End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim result = Await AnalyzeDocumentAsync(oldProject, oldDocument) Assert.False(result.HasChanges) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")> Public Async Function AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() As Task Dim source1 = " Class C Public Shared Sub Main() System.Console.WriteLine(1) Bar() End Sub End Class " Dim source2 = " Class C Public Shared Sub Main() System.Console.WriteLine(2) Bar() End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldProject = workspace.CurrentSolution.Projects.Single() Dim oldDocument = oldProject.Documents.Single() Dim documentId = oldDocument.Id Dim oldSolution = workspace.CurrentSolution Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)) ' no declaration errors (error in method body is only reported when emitting) Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")> Public Async Function AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() As Task Dim source1 = " Class C Public Shared Sub Main(x As Bar) System.Console.WriteLine(1) End Sub End Class " Dim source2 = " Class C Public Shared Sub Main(x As Bar) System.Console.WriteLine(2) End Sub End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.Single() Dim documentId = oldProject.Documents.Single().Id Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2)) Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId)) Assert.True(result.HasChanges) ' No errors reported: EnC analyzer is resilient against semantic errors. ' They will be reported by 1) compiler diagnostic analyzer 2) when emitting delta - if still present. Assert.False(result.HasChangesAndErrors) Assert.False(result.HasChangesAndSyntaxErrors) End Using End Function <Fact> Public Async Function AnalyzeDocumentAsync_AddingNewFile() As Task Dim source1 = " Namespace N Class C Public Shared Sub Main() End Sub End Class End Namespace " Dim source2 = " Class D End Class " Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition) Dim oldSolution = workspace.CurrentSolution Dim oldProject = oldSolution.Projects.Single() Dim newDocId = DocumentId.CreateNewId(oldProject.Id) Dim newSolution = oldSolution.AddDocument(newDocId, "goo.vb", SourceText.From(source2)) workspace.TryApplyChanges(newSolution) Dim newProject = newSolution.Projects.Single() Dim changes = newProject.GetChanges(oldProject) Assert.Equal(2, newProject.Documents.Count()) Assert.Equal(0, changes.GetChangedDocuments().Count()) Assert.Equal(1, changes.GetAddedDocuments().Count()) Dim changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()) Dim result = New List(Of DocumentAnalysisResults)() For Each changedDocumentId In changedDocuments result.Add(Await AnalyzeDocumentAsync(oldProject, newProject.GetDocument(changedDocumentId))) Next Assert.True(result.IsSingle()) Assert.Empty(result.Single().RudeEditErrors) End Using End Function End Class End Namespace
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, ActiveStatementsMap oldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, AsyncLazy<ActiveStatementsMap> lazyOldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } var capabilities = await lazyCapabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); var oldActiveStatementMap = await lazyOldActiveStatementMap.GetValueAsync(cancellationToken).ConfigureAwait(false); // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } private void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/EditAndContinueCapabilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 4, /// <summary> /// Adding, updating and deleting of custom attributes (as distinct from pseudo-custom attributes) /// </summary> ChangeCustomAttributes = 1 << 5, /// <summary> /// Whether the runtime supports updating the Param table, and hence related edits (eg parameter renames) /// </summary> UpdateParameters = 1 << 6, } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 4, /// <summary> /// Adding, updating and deleting of custom attributes (as distinct from pseudo-custom attributes) /// </summary> ChangeCustomAttributes = 1 << 5, /// <summary> /// Whether the runtime supports updating the Param table, and hence related edits (eg parameter renames) /// </summary> UpdateParameters = 1 << 6, } internal static class EditAndContinueCapabilitiesParser { public static EditAndContinueCapabilities Parse(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, "UpdateParameters" => EditAndContinueCapabilities.UpdateParameters, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/EditAndContinueDocumentAnalysesCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements) { _baseActiveStatements = baseActiveStatements; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync(CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, capabilities, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync(CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans, capabilities); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans) && analysis.capabilities == capabilities) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); return await analyzer.AnalyzeDocumentAsync(baseProject, baseActiveStatements, document, activeStatementSpans, capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans, capabilities); return lazyResults; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; private readonly AsyncLazy<EditAndContinueCapabilities> _capabilities; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements, AsyncLazy<EditAndContinueCapabilities> capabilities) { _baseActiveStatements = baseActiveStatements; _capabilities = capabilities; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync( CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync( CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans)) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); return await analyzer.AnalyzeDocumentAsync(baseProject, _baseActiveStatements, document, activeStatementSpans, _capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans); return lazyResults; } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var runtimeCapabilities = await debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); var capabilities = ParseCapabilities(runtimeCapabilities); // For now, runtimes aren't returning capabilities, we just fall back to a known set. if (capabilities == EditAndContinueCapabilities.None) { capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.NewTypeDefinition; } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, capabilities, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); // internal for testing internal static EditAndContinueCapabilities ParseCapabilities(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, "UpdateParameters" => EditAndContinueCapabilities.UpdateParameters, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateEntered(out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateEntered(out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/EditSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions; /// <summary> /// Lazily calculated map of base active statements. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; Telemetry = telemetry; _nonRemappableRegions = debuggingSession.NonRemappableRegions; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, _nonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); var result = EditAndContinueCapabilitiesParser.Parse(capabilities); // For now, runtimes aren't returning capabilities, we just fall back to a known set. // https://github.com/dotnet/roslyn/issues/54386 if (result == EditAndContinueCapabilities.None) { result = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.NewTypeDefinition; } return result; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EditAndContinue/IEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IEditAndContinueAnalyzer : ILanguageService { Task<DocumentAnalysisResults> AnalyzeDocumentAsync(Project baseProject, ActiveStatementsMap baseActiveStatements, Document document, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken); ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, 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.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IEditAndContinueAnalyzer : ILanguageService { Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project baseProject, AsyncLazy<ActiveStatementsMap> lazyBaseActiveStatements, Document document, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken); ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken); } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; namespace Roslyn.Utilities { internal static class AsyncLazy { public static AsyncLazy<T> Create<T>(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult) => new(asynchronousComputeFunction, cacheResult); } /// <summary> /// Represents a value that can be retrieved synchronously or asynchronously by many clients. /// The value will be computed on-demand the moment the first client asks for it. While being /// computed, more clients can request the value. As long as there are outstanding clients the /// underlying computation will proceed. If all outstanding clients cancel their request then /// the underlying value computation will be cancelled as well. /// /// Creators of an <see cref="AsyncLazy{T}" /> can specify whether the result of the computation is /// cached for future requests or not. Choosing to not cache means the computation functions are kept /// alive, whereas caching means the value (but not functions) are kept alive once complete. /// </summary> internal sealed class AsyncLazy<T> : ValueSource<T> { /// <summary> /// The underlying function that starts an asynchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it. Otherwise, /// it is kept around in case the value needs to be computed again. /// </summary> private Func<CancellationToken, Task<T>>? _asynchronousComputeFunction; /// <summary> /// The underlying function that starts a synchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it, or if we /// didn't get any synchronous function given to us in the first place. /// </summary> private Func<CancellationToken, T>? _synchronousComputeFunction; /// <summary> /// Whether or not we should keep the value around once we've computed it. /// </summary> private readonly bool _cacheResult; /// <summary> /// The Task that holds the cached result. /// </summary> private Task<T>? _cachedResult; /// <summary> /// Mutex used to protect reading and writing to all mutable objects and fields. Traces /// indicate that there's negligible contention on this lock, hence we can save some memory /// by using a single lock for all AsyncLazy instances. Only trivial and non-reentrant work /// should be done while holding the lock. /// </summary> private static readonly NonReentrantLock s_gate = new(useThisInstanceForSynchronization: true); /// <summary> /// The hash set of all currently outstanding asynchronous requests. Null if there are no requests, /// and will never be empty. /// </summary> private HashSet<Request>? _requests; /// <summary> /// If an asynchronous request is active, the CancellationTokenSource that allows for /// cancelling the underlying computation. /// </summary> private CancellationTokenSource? _asynchronousComputationCancellationSource; /// <summary> /// Whether a computation is active or queued on any thread, whether synchronous or /// asynchronous. /// </summary> private bool _computationActive; /// <summary> /// Creates an AsyncLazy that always returns the value, analogous to <see cref="Task.FromResult{T}" />. /// </summary> public AsyncLazy(T value) { _cacheResult = true; _cachedResult = Task.FromResult(value); } public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult) : this(asynchronousComputeFunction, synchronousComputeFunction: null, cacheResult: cacheResult) { } /// <summary> /// Creates an AsyncLazy that supports both asynchronous computation and inline synchronous /// computation. /// </summary> /// <param name="asynchronousComputeFunction">A function called to start the asynchronous /// computation. This function should be cheap and non-blocking.</param> /// <param name="synchronousComputeFunction">A function to do the work synchronously, which /// is allowed to block. This function should not be implemented by a simple Wait on the /// asynchronous value. If that's all you are doing, just don't pass a synchronous function /// in the first place.</param> /// <param name="cacheResult">Whether the result should be cached once the computation is /// complete.</param> public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, Func<CancellationToken, T>? synchronousComputeFunction, bool cacheResult) { Contract.ThrowIfNull(asynchronousComputeFunction); _asynchronousComputeFunction = asynchronousComputeFunction; _synchronousComputeFunction = synchronousComputeFunction; _cacheResult = cacheResult; } #region Lock Wrapper for Invariant Checking /// <summary> /// Takes the lock for this object and if acquired validates the invariants of this class. /// </summary> private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken) { s_gate.Wait(cancellationToken); AssertInvariants_NoLock(); return new WaitThatValidatesInvariants(this); } private struct WaitThatValidatesInvariants : IDisposable { private readonly AsyncLazy<T> _asyncLazy; public WaitThatValidatesInvariants(AsyncLazy<T> asyncLazy) => _asyncLazy = asyncLazy; public void Dispose() { _asyncLazy.AssertInvariants_NoLock(); s_gate.Release(); } } private void AssertInvariants_NoLock() { // Invariant #1: thou shalt never have an asynchronous computation running without it // being considered a computation Contract.ThrowIfTrue(_asynchronousComputationCancellationSource != null && !_computationActive); // Invariant #2: thou shalt never waste memory holding onto empty HashSets Contract.ThrowIfTrue(_requests != null && _requests.Count == 0); // Invariant #3: thou shalt never have an request if there is not // something trying to compute it Contract.ThrowIfTrue(_requests != null && !_computationActive); // Invariant #4: thou shalt never have a cached value and any computation function Contract.ThrowIfTrue(_cachedResult != null && (_synchronousComputeFunction != null || _asynchronousComputeFunction != null)); // Invariant #5: thou shalt never have a synchronous computation function but not an // asynchronous one Contract.ThrowIfTrue(_asynchronousComputeFunction == null && _synchronousComputeFunction != null); } #endregion public override bool TryGetValue([MaybeNullWhen(false)] out T result) { // No need to lock here since this is only a fast check to // see if the result is already computed. if (_cachedResult != null) { result = _cachedResult.Result; return true; } result = default; return false; } public override T GetValue(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // If the value is already available, return it immediately if (TryGetValue(out var value)) { return value; } Request? request = null; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult.Result; } // If there is an existing computation active, we'll just create another request if (_computationActive) { request = CreateNewRequest_NoLock(); } else if (_synchronousComputeFunction == null) { // A synchronous request, but we have no synchronous function. Start off the async work request = CreateNewRequest_NoLock(); newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } else { // We will do the computation here _computationActive = true; } } // If we simply created a new asynchronous request, so wait for it. Yes, we're blocking the thread // but we don't want multiple threads attempting to compute the same thing. if (request != null) { request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); // Since we already registered for cancellation, it's possible that the registration has // cancelled this new computation if we were the only requester. if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken); } // The reason we have synchronous codepaths in AsyncLazy is to support the synchronous requests for syntax trees // that we may get from the compiler. Thus, it's entirely possible that this will be requested by the compiler or // an analyzer on the background thread when another part of the IDE is requesting the same tree asynchronously. // In that case we block the synchronous request on the asynchronous request, since that's better than alternatives. return request.Task.WaitAndGetResult_CanCallOnBackground(cancellationToken); } else { Contract.ThrowIfNull(_synchronousComputeFunction); T result; // We are the active computation, so let's go ahead and compute. try { result = _synchronousComputeFunction(cancellationToken); } catch (OperationCanceledException) { // This cancelled for some reason. We don't care why, but // it means anybody else waiting for this result isn't going to get it // from us. using (TakeLock(CancellationToken.None)) { _computationActive = false; if (_requests != null) { // There's a possible improvement here: there might be another synchronous caller who // also wants the value. We might consider stealing their thread rather than punting // to the thread pool. newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: null, callerCancellationToken: cancellationToken); } throw; } catch (Exception ex) { // We faulted for some unknown reason. We should simply fault everything. CompleteWithTask(Task.FromException<T>(ex), CancellationToken.None); throw; } // We have a value, so complete CompleteWithTask(Task.FromResult(result), CancellationToken.None); // Optimization: if they did cancel and the computation never observed it, let's throw so we don't keep // processing a value somebody never wanted cancellationToken.ThrowIfCancellationRequested(); return result; } } private Request CreateNewRequest_NoLock() { if (_requests == null) { _requests = new HashSet<Request>(); } var request = new Request(); _requests.Add(request); return request; } public override Task<T> GetValueAsync(CancellationToken cancellationToken) { // Optimization: if we're already cancelled, do not pass go if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<T>(cancellationToken); } // Avoid taking the lock if a cached value is available var cachedResult = _cachedResult; if (cachedResult != null) { return cachedResult; } Request request; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult; } request = CreateNewRequest_NoLock(); // If we have either synchronous or asynchronous work current in flight, we don't need to do anything. // Otherwise, we shall start an asynchronous computation for this if (!_computationActive) { newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } // We now have the request counted for, register for cancellation. It is critical this is // done outside the lock, as our registration may immediately fire and we want to avoid the // reentrancy request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken); } return request.Task; } private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock() { Contract.ThrowIfTrue(_computationActive); Contract.ThrowIfNull(_asynchronousComputeFunction); _asynchronousComputationCancellationSource = new CancellationTokenSource(); _computationActive = true; return new AsynchronousComputationToStart(_asynchronousComputeFunction, _asynchronousComputationCancellationSource); } private struct AsynchronousComputationToStart { public readonly Func<CancellationToken, Task<T>> AsynchronousComputeFunction; public readonly CancellationTokenSource CancellationTokenSource; public AsynchronousComputationToStart(Func<CancellationToken, Task<T>> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource) { AsynchronousComputeFunction = asynchronousComputeFunction; CancellationTokenSource = cancellationTokenSource; } } private void StartAsynchronousComputation(AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken) { var cancellationToken = computationToStart.CancellationTokenSource.Token; // DO NOT ACCESS ANY FIELDS OR STATE BEYOND THIS POINT. Since this function // runs unsynchronized, it's possible that during this function this request // might be cancelled, and then a whole additional request might start and // complete inline, and cache the result. By grabbing state before we check // the cancellation token, we can be assured that we are only operating on // a state that was complete. try { cancellationToken.ThrowIfCancellationRequested(); var task = computationToStart.AsynchronousComputeFunction(cancellationToken); // As an optimization, if the task is already completed, mark the // request as being completed as well. // // Note: we want to do this before we do the .ContinueWith below. That way, // when the async call to CompleteWithTask runs, it sees that we've already // completed and can bail immediately. if (requestToCompleteSynchronously != null && task.IsCompleted) { using (TakeLock(CancellationToken.None)) { task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } requestToCompleteSynchronously.CompleteFromTask(task); } // We avoid creating a full closure just to pass the token along // Also, use TaskContinuationOptions.ExecuteSynchronously so that we inline // the continuation if asynchronousComputeFunction completes synchronously task.ContinueWith( (t, s) => CompleteWithTask(t, ((CancellationTokenSource)s!).Token), computationToStart.CancellationTokenSource, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken) { // The underlying computation cancelled with the correct token, but we must ourselves ensure that the caller // on our stack gets an OperationCanceledException thrown with the right token callerCancellationToken.ThrowIfCancellationRequested(); // We can only be here if the computation was cancelled, which means all requests for the value // must have been cancelled. Therefore, the ThrowIfCancellationRequested above must have thrown // because that token from the requester was cancelled. throw ExceptionUtilities.Unreachable; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } private void CompleteWithTask(Task<T> task, CancellationToken cancellationToken) { IEnumerable<Request> requestsToComplete; using (TakeLock(cancellationToken)) { // If the underlying computation was cancelled, then all state was already updated in OnAsynchronousRequestCancelled // and there is no new work to do here. We *must* use the local one since this completion may be running far after // the background computation was cancelled and a new one might have already been enqueued. We must do this // check here under the lock to ensure proper synchronization with OnAsynchronousRequestCancelled. cancellationToken.ThrowIfCancellationRequested(); // The computation is complete, so get all requests to complete and null out the list. We'll create another one // later if it's needed requestsToComplete = _requests ?? (IEnumerable<Request>)Array.Empty<Request>(); _requests = null; // The computations are done _asynchronousComputationCancellationSource = null; _computationActive = false; task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } // Complete the requests outside the lock. It's not necessary to do this (none of this is touching any shared state) // but there's no reason to hold the lock so we could reduce any theoretical lock contention. foreach (var requestToComplete in requestsToComplete) { requestToComplete.CompleteFromTask(task); } } [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] private Task<T> GetCachedValueAndCacheThisValueIfNoneCached_NoLock(Task<T> task) { if (_cachedResult != null) { return _cachedResult; } else { if (_cacheResult && task.Status == TaskStatus.RanToCompletion) { // Hold onto the completed task. We can get rid of the computation functions for good _cachedResult = task; _asynchronousComputeFunction = null; _synchronousComputeFunction = null; } return task; } } private void OnAsynchronousRequestCancelled(object? state) { var request = (Request)state!; CancellationTokenSource? cancellationTokenSource = null; using (TakeLock(CancellationToken.None)) { // Now try to remove it. It's possible that requests may already be null. You could // imagine that cancellation was requested, but before we could acquire the lock // here the computation completed and the entire CompleteWithTask synchronized // block ran. In that case, the requests collection may already be null, or it // (even scarier!) may have been replaced with another collection because another // computation has started. if (_requests != null) { if (_requests.Remove(request)) { if (_requests.Count == 0) { _requests = null; if (_asynchronousComputationCancellationSource != null) { cancellationTokenSource = _asynchronousComputationCancellationSource; _asynchronousComputationCancellationSource = null; _computationActive = false; } } } } } request.Cancel(); cancellationTokenSource?.Cancel(); } /// <remarks> /// This inherits from <see cref="TaskCompletionSource{TResult}"/> to avoid allocating two objects when we can just use one. /// The public surface area of <see cref="TaskCompletionSource{TResult}"/> should probably be avoided in favor of the public /// methods on this class for correct behavior. /// </remarks> private sealed class Request : TaskCompletionSource<T> { /// <summary> /// The <see cref="CancellationToken"/> associated with this request. This field will be initialized before /// any cancellation is observed from the token. /// </summary> private CancellationToken _cancellationToken; private CancellationTokenRegistration _cancellationTokenRegistration; // We want to always run continuations asynchronously. Running them synchronously could result in deadlocks: // if we're looping through a bunch of Requests and completing them one by one, and the continuation for the // first Request was then blocking waiting for a later Request, we would hang. It also could cause performance // issues. If the first request then consumes a lot of CPU time, we're not letting other Requests complete that // could use another CPU core at the same time. public Request() : base(TaskCreationOptions.RunContinuationsAsynchronously) { } public void RegisterForCancellation(Action<object?> callback, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _cancellationTokenRegistration = cancellationToken.Register(callback, this); } public void CompleteFromTask(Task<T> task) { // As an optimization, we'll cancel the request even we did get a value for it. // That way things abort sooner. if (task.IsCanceled || _cancellationToken.IsCancellationRequested) { Cancel(); } else if (task.IsFaulted) { // TrySetException wraps its argument in an AggregateException, so we pass the inner exceptions from // the antecedent to avoid wrapping in two layers of AggregateException. RoslynDebug.AssertNotNull(task.Exception); if (task.Exception.InnerExceptions.Count > 0) this.TrySetException(task.Exception.InnerExceptions); else this.TrySetException(task.Exception); } else { this.TrySetResult(task.Result); } _cancellationTokenRegistration.Dispose(); } public void Cancel() => this.TrySetCanceled(_cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; namespace Roslyn.Utilities { internal static class AsyncLazy { public static AsyncLazy<T> Create<T>(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult) => new(asynchronousComputeFunction, cacheResult); public static AsyncLazy<T> Create<T>(T value) => new(value); } /// <summary> /// Represents a value that can be retrieved synchronously or asynchronously by many clients. /// The value will be computed on-demand the moment the first client asks for it. While being /// computed, more clients can request the value. As long as there are outstanding clients the /// underlying computation will proceed. If all outstanding clients cancel their request then /// the underlying value computation will be cancelled as well. /// /// Creators of an <see cref="AsyncLazy{T}" /> can specify whether the result of the computation is /// cached for future requests or not. Choosing to not cache means the computation functions are kept /// alive, whereas caching means the value (but not functions) are kept alive once complete. /// </summary> internal sealed class AsyncLazy<T> : ValueSource<T> { /// <summary> /// The underlying function that starts an asynchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it. Otherwise, /// it is kept around in case the value needs to be computed again. /// </summary> private Func<CancellationToken, Task<T>>? _asynchronousComputeFunction; /// <summary> /// The underlying function that starts a synchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it, or if we /// didn't get any synchronous function given to us in the first place. /// </summary> private Func<CancellationToken, T>? _synchronousComputeFunction; /// <summary> /// Whether or not we should keep the value around once we've computed it. /// </summary> private readonly bool _cacheResult; /// <summary> /// The Task that holds the cached result. /// </summary> private Task<T>? _cachedResult; /// <summary> /// Mutex used to protect reading and writing to all mutable objects and fields. Traces /// indicate that there's negligible contention on this lock, hence we can save some memory /// by using a single lock for all AsyncLazy instances. Only trivial and non-reentrant work /// should be done while holding the lock. /// </summary> private static readonly NonReentrantLock s_gate = new(useThisInstanceForSynchronization: true); /// <summary> /// The hash set of all currently outstanding asynchronous requests. Null if there are no requests, /// and will never be empty. /// </summary> private HashSet<Request>? _requests; /// <summary> /// If an asynchronous request is active, the CancellationTokenSource that allows for /// cancelling the underlying computation. /// </summary> private CancellationTokenSource? _asynchronousComputationCancellationSource; /// <summary> /// Whether a computation is active or queued on any thread, whether synchronous or /// asynchronous. /// </summary> private bool _computationActive; /// <summary> /// Creates an AsyncLazy that always returns the value, analogous to <see cref="Task.FromResult{T}" />. /// </summary> public AsyncLazy(T value) { _cacheResult = true; _cachedResult = Task.FromResult(value); } public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult) : this(asynchronousComputeFunction, synchronousComputeFunction: null, cacheResult: cacheResult) { } /// <summary> /// Creates an AsyncLazy that supports both asynchronous computation and inline synchronous /// computation. /// </summary> /// <param name="asynchronousComputeFunction">A function called to start the asynchronous /// computation. This function should be cheap and non-blocking.</param> /// <param name="synchronousComputeFunction">A function to do the work synchronously, which /// is allowed to block. This function should not be implemented by a simple Wait on the /// asynchronous value. If that's all you are doing, just don't pass a synchronous function /// in the first place.</param> /// <param name="cacheResult">Whether the result should be cached once the computation is /// complete.</param> public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, Func<CancellationToken, T>? synchronousComputeFunction, bool cacheResult) { Contract.ThrowIfNull(asynchronousComputeFunction); _asynchronousComputeFunction = asynchronousComputeFunction; _synchronousComputeFunction = synchronousComputeFunction; _cacheResult = cacheResult; } #region Lock Wrapper for Invariant Checking /// <summary> /// Takes the lock for this object and if acquired validates the invariants of this class. /// </summary> private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken) { s_gate.Wait(cancellationToken); AssertInvariants_NoLock(); return new WaitThatValidatesInvariants(this); } private struct WaitThatValidatesInvariants : IDisposable { private readonly AsyncLazy<T> _asyncLazy; public WaitThatValidatesInvariants(AsyncLazy<T> asyncLazy) => _asyncLazy = asyncLazy; public void Dispose() { _asyncLazy.AssertInvariants_NoLock(); s_gate.Release(); } } private void AssertInvariants_NoLock() { // Invariant #1: thou shalt never have an asynchronous computation running without it // being considered a computation Contract.ThrowIfTrue(_asynchronousComputationCancellationSource != null && !_computationActive); // Invariant #2: thou shalt never waste memory holding onto empty HashSets Contract.ThrowIfTrue(_requests != null && _requests.Count == 0); // Invariant #3: thou shalt never have an request if there is not // something trying to compute it Contract.ThrowIfTrue(_requests != null && !_computationActive); // Invariant #4: thou shalt never have a cached value and any computation function Contract.ThrowIfTrue(_cachedResult != null && (_synchronousComputeFunction != null || _asynchronousComputeFunction != null)); // Invariant #5: thou shalt never have a synchronous computation function but not an // asynchronous one Contract.ThrowIfTrue(_asynchronousComputeFunction == null && _synchronousComputeFunction != null); } #endregion public override bool TryGetValue([MaybeNullWhen(false)] out T result) { // No need to lock here since this is only a fast check to // see if the result is already computed. if (_cachedResult != null) { result = _cachedResult.Result; return true; } result = default; return false; } public override T GetValue(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // If the value is already available, return it immediately if (TryGetValue(out var value)) { return value; } Request? request = null; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult.Result; } // If there is an existing computation active, we'll just create another request if (_computationActive) { request = CreateNewRequest_NoLock(); } else if (_synchronousComputeFunction == null) { // A synchronous request, but we have no synchronous function. Start off the async work request = CreateNewRequest_NoLock(); newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } else { // We will do the computation here _computationActive = true; } } // If we simply created a new asynchronous request, so wait for it. Yes, we're blocking the thread // but we don't want multiple threads attempting to compute the same thing. if (request != null) { request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); // Since we already registered for cancellation, it's possible that the registration has // cancelled this new computation if we were the only requester. if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken); } // The reason we have synchronous codepaths in AsyncLazy is to support the synchronous requests for syntax trees // that we may get from the compiler. Thus, it's entirely possible that this will be requested by the compiler or // an analyzer on the background thread when another part of the IDE is requesting the same tree asynchronously. // In that case we block the synchronous request on the asynchronous request, since that's better than alternatives. return request.Task.WaitAndGetResult_CanCallOnBackground(cancellationToken); } else { Contract.ThrowIfNull(_synchronousComputeFunction); T result; // We are the active computation, so let's go ahead and compute. try { result = _synchronousComputeFunction(cancellationToken); } catch (OperationCanceledException) { // This cancelled for some reason. We don't care why, but // it means anybody else waiting for this result isn't going to get it // from us. using (TakeLock(CancellationToken.None)) { _computationActive = false; if (_requests != null) { // There's a possible improvement here: there might be another synchronous caller who // also wants the value. We might consider stealing their thread rather than punting // to the thread pool. newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: null, callerCancellationToken: cancellationToken); } throw; } catch (Exception ex) { // We faulted for some unknown reason. We should simply fault everything. CompleteWithTask(Task.FromException<T>(ex), CancellationToken.None); throw; } // We have a value, so complete CompleteWithTask(Task.FromResult(result), CancellationToken.None); // Optimization: if they did cancel and the computation never observed it, let's throw so we don't keep // processing a value somebody never wanted cancellationToken.ThrowIfCancellationRequested(); return result; } } private Request CreateNewRequest_NoLock() { if (_requests == null) { _requests = new HashSet<Request>(); } var request = new Request(); _requests.Add(request); return request; } public override Task<T> GetValueAsync(CancellationToken cancellationToken) { // Optimization: if we're already cancelled, do not pass go if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<T>(cancellationToken); } // Avoid taking the lock if a cached value is available var cachedResult = _cachedResult; if (cachedResult != null) { return cachedResult; } Request request; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult; } request = CreateNewRequest_NoLock(); // If we have either synchronous or asynchronous work current in flight, we don't need to do anything. // Otherwise, we shall start an asynchronous computation for this if (!_computationActive) { newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } // We now have the request counted for, register for cancellation. It is critical this is // done outside the lock, as our registration may immediately fire and we want to avoid the // reentrancy request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); if (newAsynchronousComputation != null) { StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken); } return request.Task; } private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock() { Contract.ThrowIfTrue(_computationActive); Contract.ThrowIfNull(_asynchronousComputeFunction); _asynchronousComputationCancellationSource = new CancellationTokenSource(); _computationActive = true; return new AsynchronousComputationToStart(_asynchronousComputeFunction, _asynchronousComputationCancellationSource); } private struct AsynchronousComputationToStart { public readonly Func<CancellationToken, Task<T>> AsynchronousComputeFunction; public readonly CancellationTokenSource CancellationTokenSource; public AsynchronousComputationToStart(Func<CancellationToken, Task<T>> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource) { AsynchronousComputeFunction = asynchronousComputeFunction; CancellationTokenSource = cancellationTokenSource; } } private void StartAsynchronousComputation(AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken) { var cancellationToken = computationToStart.CancellationTokenSource.Token; // DO NOT ACCESS ANY FIELDS OR STATE BEYOND THIS POINT. Since this function // runs unsynchronized, it's possible that during this function this request // might be cancelled, and then a whole additional request might start and // complete inline, and cache the result. By grabbing state before we check // the cancellation token, we can be assured that we are only operating on // a state that was complete. try { cancellationToken.ThrowIfCancellationRequested(); var task = computationToStart.AsynchronousComputeFunction(cancellationToken); // As an optimization, if the task is already completed, mark the // request as being completed as well. // // Note: we want to do this before we do the .ContinueWith below. That way, // when the async call to CompleteWithTask runs, it sees that we've already // completed and can bail immediately. if (requestToCompleteSynchronously != null && task.IsCompleted) { using (TakeLock(CancellationToken.None)) { task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } requestToCompleteSynchronously.CompleteFromTask(task); } // We avoid creating a full closure just to pass the token along // Also, use TaskContinuationOptions.ExecuteSynchronously so that we inline // the continuation if asynchronousComputeFunction completes synchronously task.ContinueWith( (t, s) => CompleteWithTask(t, ((CancellationTokenSource)s!).Token), computationToStart.CancellationTokenSource, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken) { // The underlying computation cancelled with the correct token, but we must ourselves ensure that the caller // on our stack gets an OperationCanceledException thrown with the right token callerCancellationToken.ThrowIfCancellationRequested(); // We can only be here if the computation was cancelled, which means all requests for the value // must have been cancelled. Therefore, the ThrowIfCancellationRequested above must have thrown // because that token from the requester was cancelled. throw ExceptionUtilities.Unreachable; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } private void CompleteWithTask(Task<T> task, CancellationToken cancellationToken) { IEnumerable<Request> requestsToComplete; using (TakeLock(cancellationToken)) { // If the underlying computation was cancelled, then all state was already updated in OnAsynchronousRequestCancelled // and there is no new work to do here. We *must* use the local one since this completion may be running far after // the background computation was cancelled and a new one might have already been enqueued. We must do this // check here under the lock to ensure proper synchronization with OnAsynchronousRequestCancelled. cancellationToken.ThrowIfCancellationRequested(); // The computation is complete, so get all requests to complete and null out the list. We'll create another one // later if it's needed requestsToComplete = _requests ?? (IEnumerable<Request>)Array.Empty<Request>(); _requests = null; // The computations are done _asynchronousComputationCancellationSource = null; _computationActive = false; task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } // Complete the requests outside the lock. It's not necessary to do this (none of this is touching any shared state) // but there's no reason to hold the lock so we could reduce any theoretical lock contention. foreach (var requestToComplete in requestsToComplete) { requestToComplete.CompleteFromTask(task); } } [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] private Task<T> GetCachedValueAndCacheThisValueIfNoneCached_NoLock(Task<T> task) { if (_cachedResult != null) { return _cachedResult; } else { if (_cacheResult && task.Status == TaskStatus.RanToCompletion) { // Hold onto the completed task. We can get rid of the computation functions for good _cachedResult = task; _asynchronousComputeFunction = null; _synchronousComputeFunction = null; } return task; } } private void OnAsynchronousRequestCancelled(object? state) { var request = (Request)state!; CancellationTokenSource? cancellationTokenSource = null; using (TakeLock(CancellationToken.None)) { // Now try to remove it. It's possible that requests may already be null. You could // imagine that cancellation was requested, but before we could acquire the lock // here the computation completed and the entire CompleteWithTask synchronized // block ran. In that case, the requests collection may already be null, or it // (even scarier!) may have been replaced with another collection because another // computation has started. if (_requests != null) { if (_requests.Remove(request)) { if (_requests.Count == 0) { _requests = null; if (_asynchronousComputationCancellationSource != null) { cancellationTokenSource = _asynchronousComputationCancellationSource; _asynchronousComputationCancellationSource = null; _computationActive = false; } } } } } request.Cancel(); cancellationTokenSource?.Cancel(); } /// <remarks> /// This inherits from <see cref="TaskCompletionSource{TResult}"/> to avoid allocating two objects when we can just use one. /// The public surface area of <see cref="TaskCompletionSource{TResult}"/> should probably be avoided in favor of the public /// methods on this class for correct behavior. /// </remarks> private sealed class Request : TaskCompletionSource<T> { /// <summary> /// The <see cref="CancellationToken"/> associated with this request. This field will be initialized before /// any cancellation is observed from the token. /// </summary> private CancellationToken _cancellationToken; private CancellationTokenRegistration _cancellationTokenRegistration; // We want to always run continuations asynchronously. Running them synchronously could result in deadlocks: // if we're looping through a bunch of Requests and completing them one by one, and the continuation for the // first Request was then blocking waiting for a later Request, we would hang. It also could cause performance // issues. If the first request then consumes a lot of CPU time, we're not letting other Requests complete that // could use another CPU core at the same time. public Request() : base(TaskCreationOptions.RunContinuationsAsynchronously) { } public void RegisterForCancellation(Action<object?> callback, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _cancellationTokenRegistration = cancellationToken.Register(callback, this); } public void CompleteFromTask(Task<T> task) { // As an optimization, we'll cancel the request even we did get a value for it. // That way things abort sooner. if (task.IsCanceled || _cancellationToken.IsCancellationRequested) { Cancel(); } else if (task.IsFaulted) { // TrySetException wraps its argument in an AggregateException, so we pass the inner exceptions from // the antecedent to avoid wrapping in two layers of AggregateException. RoslynDebug.AssertNotNull(task.Exception); if (task.Exception.InnerExceptions.Count > 0) this.TrySetException(task.Exception.InnerExceptions); else this.TrySetException(task.Exception); } else { this.TrySetResult(task.Result); } _cancellationTokenRegistration.Dispose(); } public void Cancel() => this.TrySetCanceled(_cancellationToken); } } }
1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Test/Emit/Emit/ResourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class ResourceTests : CSharpTestBase { [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void DefaultVersionResource() { string source = @" public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerNoAttrs", options: TestOptions.ReleaseExe); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; string mftData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint mftSize; IntPtr mftRsrc = Win32Res.GetResource(lib, "#1", "#24", out mftSize); mftData = Win32Res.ManifestResourceToXml(mftRsrc, mftSize); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""612""> <VS_FIXEDFILEINFO FileVersionMS=""00000000"" FileVersionLS=""00000000"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" /> <KeyValuePair Key=""FileDescription"" Value="" "" /> <KeyValuePair Key=""FileVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value="" "" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""ProductVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""Assembly Version"" Value=""0.0.0.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"; Assert.Equal(expected, mftData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal(" ", fileVer.LegalCopyright); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourcesInCoff() { //this is to test that resources coming from a COFF can be added to a binary. string source = @" class C { } "; var c1 = CreateCompilation(source, assemblyName: "Win32WithCoff", options: TestOptions.ReleaseDll); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { var memStream = new MemoryStream(TestResources.General.nativeCOFFResources); c1.Emit(output, win32Resources: memStream); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the resources //we expect are present. Also need to check that the actual contents of at least one of the resources //is good. That tests our processing of the relocations. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint stringTableSize; IntPtr stringTable = Win32Res.GetResource(lib, "#1", "#6", out stringTableSize); Assert.NotEqual(default, stringTable); uint elevenSize; IntPtr elevenRsrc = Win32Res.GetResource(lib, "#1", "#11", out elevenSize); Assert.NotEqual(default, elevenRsrc); uint wevtSize; IntPtr wevtRsrc = Win32Res.GetResource(lib, "#1", "WEVT_TEMPLATE", out wevtSize); Assert.NotEqual(default, wevtRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""1104""> <VS_FIXEDFILEINFO FileVersionMS=""000b0000"" FileVersionLS=""eacc0000"" ProductVersionMS=""000b0000"" ProductVersionLS=""eacc0000"" /> <KeyValuePair Key=""CompanyName"" Value=""Microsoft Corporation"" /> <KeyValuePair Key=""FileDescription"" Value=""Team Foundation Server Object Model"" /> <KeyValuePair Key=""FileVersion"" Value=""11.0.60108.0 built by: TOOLSET_ROSLYN(GNAMBOO-DEV-GNAMBOO)"" /> <KeyValuePair Key=""InternalName"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""LegalCopyright"" Value=""© Microsoft Corporation. All rights reserved."" /> <KeyValuePair Key=""OriginalFilename"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""ProductName"" Value=""Microsoft® Visual Studio® 2012"" /> <KeyValuePair Key=""ProductVersion"" Value=""11.0.60108.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal("Microsoft Corporation", fileVer.CompanyName); } [Fact] public void FaultyResourceDataProvider() { var c1 = CreateCompilation(""); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => { throw new Exception("bad stuff"); }, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'bad stuff' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", "bad stuff") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => null, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'Resource data provider should return non-null stream' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream) ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier_EmbeddedResource() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("A", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS7041_DuplicateManifestResourceFileName() { var c1 = CSharpCompilation.Create("goo", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void NoDuplicateManifestResourceFileNameDiagnosticForEmbeddedResources() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("B", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify(); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("B", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify(); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501"), WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] [Fact] public void CS1508_CS7041_DuplicateManifestResourceDiagnostics() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A"), // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true), new ResourceDescription("B", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo"), // error CS1508: Resource identifier 'B' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("B") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "goo.dll", dataProvider, true), }); //make sure there's no problem when the name of the primary module conflicts with a file name of an added resource. result.Diagnostics.Verify(); var netModule1 = TestReferences.SymbolsTests.netModule.netModule1; c1 = CreateCompilation("", references: new[] { netModule1 }); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "netmodule1.netmodule", dataProvider, true), }); // Native compiler gives CS0013 (FTL_MetadataEmitFailure) at Emit stage result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'netmodule1.netmodule' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("netModule1.netmodule") ); } [ConditionalFact(typeof(DesktopOnly))] public void AddManagedResource() { string source = @"public class C { static public void Main() {} }"; // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CreateCompilation(source); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var assembly = Assembly.ReflectionOnlyLoad(output.ToArray()); string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(resourceFileName, rInfo.FileName); c1 = null; } [ConditionalFact(typeof(WindowsDesktopOnly))] public void AddResourceToModule() { bool metadataOnly = false; Func<Compilation, Stream, ResourceDescription[], CodeAnalysis.Emit.EmitResult> emit; emit = (c, s, r) => c.Emit(s, manifestResources: r, options: new EmitOptions(metadataOnly: metadataOnly)); var sourceTree = SyntaxFactory.ParseSyntaxTree(""); // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false), new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); var c_mod1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod1 = new MemoryStream(); result = emit(c_mod1, output_mod1, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.True(result.Success); var mod1 = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable()); var ref_mod1 = mod1.GetReference(); Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c2 = CreateCompilation(sourceTree, new[] { ref_mod1 }, TestOptions.ReleaseDll); var output2 = new MemoryStream(); var result2 = c2.Emit(output2); Assert.True(result2.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(1, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); } var c_mod2 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod2 = new MemoryStream(); result = emit(c_mod2, output_mod2, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true) }); Assert.True(result.Success); var ref_mod2 = ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()).GetReference(); { var c3 = CreateCompilation(sourceTree, new[] { ref_mod2 }, TestOptions.ReleaseDll); var output3 = new MemoryStream(); var result3 = c3.Emit(output3); Assert.True(result3.Success); var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod2.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod2.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } var c_mod3 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod3 = new MemoryStream(); result = emit(c_mod3, output_mod3, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var mod3 = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable()); var ref_mod3 = mod3.GetReference(); Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c4 = CreateCompilation(sourceTree, new[] { ref_mod3 }, TestOptions.ReleaseDll); var output4 = new MemoryStream(); var result4 = c4.Emit(output4, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false) }); Assert.True(result4.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c5 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.ReleaseDll); var output5 = new MemoryStream(); var result5 = emit(c5, output5, null); Assert.True(result5.Success); var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } else if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseDll); var output6 = new MemoryStream(); var result6 = emit(c6, output6, null); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME") ); } result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"), // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME") ); } c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseModule); result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result6.Success); } } [Fact] public void AddManagedLinkedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, "nonExistent", () => { throw new NotSupportedException("error in data provider"); }, false) }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [Fact] public void AddManagedEmbeddedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, () => null, true), }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourceWithAttrSettings() { string source = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyFileVersion(""5.6.7.8"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] [assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] [assembly: System.Reflection.AssemblyCompany(""MossBrain"")] [assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] [assembly: System.Reflection.AssemblyCopyright(""circle C"")] [assembly: System.Reflection.AssemblyTrademark(""circle R"")] [assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerAttrs", options: TestOptions.ReleaseExe); var exeFile = Temp.CreateFile(); using (FileStream output = exeFile.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; string versionData; //Open as data IntPtr lib = IntPtr.Zero; try { lib = LoadLibraryEx(exeFile.Path, IntPtr.Zero, 0x00000002); Assert.True(lib != IntPtr.Zero, String.Format("LoadLibrary failed with HResult: {0:X}", +Marshal.GetLastWin32Error())); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""964""> <VS_FIXEDFILEINFO FileVersionMS=""00050006"" FileVersionLS=""00070008"" ProductVersionMS=""00010002"" ProductVersionLS=""00030000"" /> <KeyValuePair Key=""Comments"" Value=""A classic of magical realist literature"" /> <KeyValuePair Key=""CompanyName"" Value=""MossBrain"" /> <KeyValuePair Key=""FileDescription"" Value=""One Hundred Years of Solitude"" /> <KeyValuePair Key=""FileVersion"" Value=""5.6.7.8"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value=""circle C"" /> <KeyValuePair Key=""LegalTrademarks"" Value=""circle R"" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""ProductName"" Value=""Sound Cannon"" /> <KeyValuePair Key=""ProductVersion"" Value=""1.2.3garbage"" /> <KeyValuePair Key=""Assembly Version"" Value=""1.2.3.4"" /> </VersionResource>"; Assert.Equal(expected, versionData); } [Fact] public void ResourceProviderStreamGivesBadLength() { var backingStream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); var stream = new TestStream( canRead: true, canSeek: true, readFunc: backingStream.Read, length: 6, // Lie about the length (> backingStream.Length) getPosition: () => backingStream.Position); var c1 = CreateCompilation(""); using (new EnsureEnglishUICulture()) { var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("res", () => stream, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'res' -- 'Resource stream ended at 4 bytes, expected 6 bytes.' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("res", "Resource stream ended at 4 bytes, expected 6 bytes.").WithLocation(1, 1)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class ResourceTests : CSharpTestBase { [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void DefaultVersionResource() { string source = @" public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerNoAttrs", options: TestOptions.ReleaseExe); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; string mftData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint mftSize; IntPtr mftRsrc = Win32Res.GetResource(lib, "#1", "#24", out mftSize); mftData = Win32Res.ManifestResourceToXml(mftRsrc, mftSize); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""612""> <VS_FIXEDFILEINFO FileVersionMS=""00000000"" FileVersionLS=""00000000"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" /> <KeyValuePair Key=""FileDescription"" Value="" "" /> <KeyValuePair Key=""FileVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value="" "" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""ProductVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""Assembly Version"" Value=""0.0.0.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"; Assert.Equal(expected, mftData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal(" ", fileVer.LegalCopyright); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourcesInCoff() { //this is to test that resources coming from a COFF can be added to a binary. string source = @" class C { } "; var c1 = CreateCompilation(source, assemblyName: "Win32WithCoff", options: TestOptions.ReleaseDll); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { var memStream = new MemoryStream(TestResources.General.nativeCOFFResources); c1.Emit(output, win32Resources: memStream); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the resources //we expect are present. Also need to check that the actual contents of at least one of the resources //is good. That tests our processing of the relocations. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint stringTableSize; IntPtr stringTable = Win32Res.GetResource(lib, "#1", "#6", out stringTableSize); Assert.NotEqual(default, stringTable); uint elevenSize; IntPtr elevenRsrc = Win32Res.GetResource(lib, "#1", "#11", out elevenSize); Assert.NotEqual(default, elevenRsrc); uint wevtSize; IntPtr wevtRsrc = Win32Res.GetResource(lib, "#1", "WEVT_TEMPLATE", out wevtSize); Assert.NotEqual(default, wevtRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""1104""> <VS_FIXEDFILEINFO FileVersionMS=""000b0000"" FileVersionLS=""eacc0000"" ProductVersionMS=""000b0000"" ProductVersionLS=""eacc0000"" /> <KeyValuePair Key=""CompanyName"" Value=""Microsoft Corporation"" /> <KeyValuePair Key=""FileDescription"" Value=""Team Foundation Server Object Model"" /> <KeyValuePair Key=""FileVersion"" Value=""11.0.60108.0 built by: TOOLSET_ROSLYN(GNAMBOO-DEV-GNAMBOO)"" /> <KeyValuePair Key=""InternalName"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""LegalCopyright"" Value=""© Microsoft Corporation. All rights reserved."" /> <KeyValuePair Key=""OriginalFilename"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""ProductName"" Value=""Microsoft® Visual Studio® 2012"" /> <KeyValuePair Key=""ProductVersion"" Value=""11.0.60108.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal("Microsoft Corporation", fileVer.CompanyName); } [Fact] public void FaultyResourceDataProvider() { var c1 = CreateCompilation(""); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => { throw new Exception("bad stuff"); }, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'bad stuff' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", "bad stuff") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => null, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'Resource data provider should return non-null stream' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream) ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier_EmbeddedResource() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("A", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS7041_DuplicateManifestResourceFileName() { var c1 = CSharpCompilation.Create("goo", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void NoDuplicateManifestResourceFileNameDiagnosticForEmbeddedResources() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("B", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify(); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("B", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify(); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501"), WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] [Fact] public void CS1508_CS7041_DuplicateManifestResourceDiagnostics() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A"), // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true), new ResourceDescription("B", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo"), // error CS1508: Resource identifier 'B' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("B") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "goo.dll", dataProvider, true), }); //make sure there's no problem when the name of the primary module conflicts with a file name of an added resource. result.Diagnostics.Verify(); var netModule1 = TestReferences.SymbolsTests.netModule.netModule1; c1 = CreateCompilation("", references: new[] { netModule1 }); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "netmodule1.netmodule", dataProvider, true), }); // Native compiler gives CS0013 (FTL_MetadataEmitFailure) at Emit stage result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'netmodule1.netmodule' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("netModule1.netmodule") ); } [ConditionalFact(typeof(DesktopOnly))] public void AddManagedResource() { string source = @"public class C { static public void Main() {} }"; // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CreateCompilation(source); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var assembly = Assembly.ReflectionOnlyLoad(output.ToArray()); string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(resourceFileName, rInfo.FileName); c1 = null; } [ConditionalFact(typeof(WindowsDesktopOnly))] public void AddResourceToModule() { bool metadataOnly = false; Func<Compilation, Stream, ResourceDescription[], CodeAnalysis.Emit.EmitResult> emit; emit = (c, s, r) => c.Emit(s, manifestResources: r, options: new EmitOptions(metadataOnly: metadataOnly)); var sourceTree = SyntaxFactory.ParseSyntaxTree(""); // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false), new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); var c_mod1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod1 = new MemoryStream(); result = emit(c_mod1, output_mod1, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.True(result.Success); var mod1 = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable()); var ref_mod1 = mod1.GetReference(); Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c2 = CreateCompilation(sourceTree, new[] { ref_mod1 }, TestOptions.ReleaseDll); var output2 = new MemoryStream(); var result2 = c2.Emit(output2); Assert.True(result2.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(1, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); } var c_mod2 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod2 = new MemoryStream(); result = emit(c_mod2, output_mod2, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true) }); Assert.True(result.Success); var ref_mod2 = ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()).GetReference(); { var c3 = CreateCompilation(sourceTree, new[] { ref_mod2 }, TestOptions.ReleaseDll); var output3 = new MemoryStream(); var result3 = c3.Emit(output3); Assert.True(result3.Success); var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod2.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod2.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } var c_mod3 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod3 = new MemoryStream(); result = emit(c_mod3, output_mod3, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var mod3 = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable()); var ref_mod3 = mod3.GetReference(); Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c4 = CreateCompilation(sourceTree, new[] { ref_mod3 }, TestOptions.ReleaseDll); var output4 = new MemoryStream(); var result4 = c4.Emit(output4, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false) }); Assert.True(result4.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c5 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.ReleaseDll); var output5 = new MemoryStream(); var result5 = emit(c5, output5, null); Assert.True(result5.Success); var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } else if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseDll); var output6 = new MemoryStream(); var result6 = emit(c6, output6, null); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME") ); } result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"), // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME") ); } c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseModule); result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result6.Success); } } [Fact] public void AddManagedLinkedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, "nonExistent", () => { throw new NotSupportedException("error in data provider"); }, false) }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [Fact] public void AddManagedEmbeddedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, () => null, true), }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourceWithAttrSettings() { string source = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyFileVersion(""5.6.7.8"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] [assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] [assembly: System.Reflection.AssemblyCompany(""MossBrain"")] [assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] [assembly: System.Reflection.AssemblyCopyright(""circle C"")] [assembly: System.Reflection.AssemblyTrademark(""circle R"")] [assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerAttrs", options: TestOptions.ReleaseExe); var exeFile = Temp.CreateFile(); using (FileStream output = exeFile.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; string versionData; //Open as data IntPtr lib = IntPtr.Zero; try { lib = LoadLibraryEx(exeFile.Path, IntPtr.Zero, 0x00000002); Assert.True(lib != IntPtr.Zero, String.Format("LoadLibrary failed with HResult: {0:X}", +Marshal.GetLastWin32Error())); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""964""> <VS_FIXEDFILEINFO FileVersionMS=""00050006"" FileVersionLS=""00070008"" ProductVersionMS=""00010002"" ProductVersionLS=""00030000"" /> <KeyValuePair Key=""Comments"" Value=""A classic of magical realist literature"" /> <KeyValuePair Key=""CompanyName"" Value=""MossBrain"" /> <KeyValuePair Key=""FileDescription"" Value=""One Hundred Years of Solitude"" /> <KeyValuePair Key=""FileVersion"" Value=""5.6.7.8"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value=""circle C"" /> <KeyValuePair Key=""LegalTrademarks"" Value=""circle R"" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""ProductName"" Value=""Sound Cannon"" /> <KeyValuePair Key=""ProductVersion"" Value=""1.2.3garbage"" /> <KeyValuePair Key=""Assembly Version"" Value=""1.2.3.4"" /> </VersionResource>"; Assert.Equal(expected, versionData); } [Fact] public void ResourceProviderStreamGivesBadLength() { var backingStream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); var stream = new TestStream( canRead: true, canSeek: true, readFunc: backingStream.Read, length: 6, // Lie about the length (> backingStream.Length) getPosition: () => backingStream.Position); var c1 = CreateCompilation(""); using (new EnsureEnglishUICulture()) { var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("res", () => stream, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'res' -- 'Resource stream ended at 4 bytes, expected 6 bytes.' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("res", "Resource stream ended at 4 bytes, expected 6 bytes.").WithLocation(1, 1)); } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/VisualBasic/Portable/BoundTree/BoundReferenceAssignment.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundReferenceAssignment #If DEBUG Then Private Sub Validate() Debug.Assert(ByRefLocal.LocalSymbol.IsByRef AndAlso LValue.IsLValue AndAlso TypeSymbol.Equals(Type, LValue.Type, TypeCompareKind.ConsiderEverything)) End Sub #End If Protected Overrides Function MakeRValueImpl() As BoundExpression Return MakeRValue() End Function Public Shadows Function MakeRValue() As BoundReferenceAssignment If _IsLValue Then Return Update(ByRefLocal, LValue, False, Type) End If Return Me 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundReferenceAssignment #If DEBUG Then Private Sub Validate() Debug.Assert(ByRefLocal.LocalSymbol.IsByRef AndAlso LValue.IsLValue AndAlso TypeSymbol.Equals(Type, LValue.Type, TypeCompareKind.ConsiderEverything)) End Sub #End If Protected Overrides Function MakeRValueImpl() As BoundExpression Return MakeRValue() End Function Public Shadows Function MakeRValue() As BoundReferenceAssignment If _IsLValue Then Return Update(ByRefLocal, LValue, False, Type) End If Return Me End Function End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.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.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Utilities Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Class VisualBasicContainedLanguage Inherits ContainedLanguage Implements IVsContainedLanguageStaticEventBinding Public Sub New(bufferCoordinator As IVsTextBufferCoordinator, componentModel As IComponentModel, project As VisualStudioProject, hierarchy As IVsHierarchy, itemid As UInteger, languageServiceGuid As Guid) MyBase.New( bufferCoordinator, componentModel, componentModel.GetService(Of VisualStudioWorkspace)(), project.Id, project, ContainedLanguage.GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, VisualBasicHelperFormattingRule.Instance) End Sub Public Function AddStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=False, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.AddStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Public Function EnsureStaticEventHandler(pszClassName As String, pszObjectTypeName As String, pszObjectName As String, pszNameOfEvent As String, pszEventHandlerName As String, itemidInsertionPoint As UInteger, ByRef pbstrUniqueMemberID As String, ByRef pbstrEventBody As String, pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler Dim thisDocument = GetThisDocument() Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint) Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId) If targetDocument Is Nothing Then Throw New InvalidOperationException("Can't generate into that itemid") End If Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument, targetDocument, pszClassName, pszObjectName, pszObjectTypeName, pszNameOfEvent, pszEventHandlerName, itemidInsertionPoint, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1 pbstrEventBody = idBodyAndInsertionPoint.Item2 pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3 Return VSConstants.S_OK End Function Public Function GetStaticEventBindingsForObject(pszClassName As String, pszObjectName As String, ByRef pcMembers As Integer, ppbstrEventNames As IntPtr, ppbstrDisplayNames As IntPtr, ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject Dim members As Integer Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings( GetThisDocument(), pszClassName, pszObjectName, c.UserCancellationToken) members = eventNamesAndMemberNamesAndIds.Count() CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1)) CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2)) CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3)) End Sub) pcMembers = members Return VSConstants.S_OK End Function Public Function RemoveStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.RemoveStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Private Class VisualBasicHelperFormattingRule Inherits CompatAbstractFormattingRule Public Shared Shadows Instance As AbstractFormattingRule = New VisualBasicHelperFormattingRule() Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction) ' we need special behavior for VB due to @Helper code generation weird-ness. ' this will looking for code gen specific style to make it not so expansive If IsEndHelperPattern(node) Then Return End If Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax) If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then Return End If MyBase.AddIndentBlockOperationsSlow(list, node, nextOperation) End Sub Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then Return False End If If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then Return False End If Return True End Function Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean If Not node.HasStructuredTrivia Then Return False End If Dim method = TryCast(node, MethodBlockSyntax) If method Is Nothing OrElse method.Statements.Count <> 2 Then Return False End If Dim statementWithEndHelper = method.Statements(0) Dim endToken = statementWithEndHelper.GetFirstToken() If endToken.Kind <> SyntaxKind.EndKeyword Then Return False End If Dim helperToken = endToken.GetNextToken(includeSkipped:=True) If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then Return False End If Dim asToken = helperToken.GetNextToken(includeSkipped:=True) If asToken.Kind <> SyntaxKind.AsKeyword Then Return False End If Return True End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Utilities Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Class VisualBasicContainedLanguage Inherits ContainedLanguage Implements IVsContainedLanguageStaticEventBinding Public Sub New(bufferCoordinator As IVsTextBufferCoordinator, componentModel As IComponentModel, project As VisualStudioProject, hierarchy As IVsHierarchy, itemid As UInteger, languageServiceGuid As Guid) MyBase.New( bufferCoordinator, componentModel, componentModel.GetService(Of VisualStudioWorkspace)(), project.Id, project, ContainedLanguage.GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, VisualBasicHelperFormattingRule.Instance) End Sub Public Function AddStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=False, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.AddStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Public Function EnsureStaticEventHandler(pszClassName As String, pszObjectTypeName As String, pszObjectName As String, pszNameOfEvent As String, pszEventHandlerName As String, itemidInsertionPoint As UInteger, ByRef pbstrUniqueMemberID As String, ByRef pbstrEventBody As String, pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler Dim thisDocument = GetThisDocument() Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint) Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId) If targetDocument Is Nothing Then Throw New InvalidOperationException("Can't generate into that itemid") End If Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument, targetDocument, pszClassName, pszObjectName, pszObjectTypeName, pszNameOfEvent, pszEventHandlerName, itemidInsertionPoint, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1 pbstrEventBody = idBodyAndInsertionPoint.Item2 pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3 Return VSConstants.S_OK End Function Public Function GetStaticEventBindingsForObject(pszClassName As String, pszObjectName As String, ByRef pcMembers As Integer, ppbstrEventNames As IntPtr, ppbstrDisplayNames As IntPtr, ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject Dim members As Integer Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings( GetThisDocument(), pszClassName, pszObjectName, c.UserCancellationToken) members = eventNamesAndMemberNamesAndIds.Count() CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1)) CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2)) CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3)) End Sub) pcMembers = members Return VSConstants.S_OK End Function Public Function RemoveStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.RemoveStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Private Class VisualBasicHelperFormattingRule Inherits CompatAbstractFormattingRule Public Shared Shadows Instance As AbstractFormattingRule = New VisualBasicHelperFormattingRule() Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction) ' we need special behavior for VB due to @Helper code generation weird-ness. ' this will looking for code gen specific style to make it not so expansive If IsEndHelperPattern(node) Then Return End If Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax) If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then Return End If MyBase.AddIndentBlockOperationsSlow(list, node, nextOperation) End Sub Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then Return False End If If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then Return False End If Return True End Function Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean If Not node.HasStructuredTrivia Then Return False End If Dim method = TryCast(node, MethodBlockSyntax) If method Is Nothing OrElse method.Statements.Count <> 2 Then Return False End If Dim statementWithEndHelper = method.Statements(0) Dim endToken = statementWithEndHelper.GetFirstToken() If endToken.Kind <> SyntaxKind.EndKeyword Then Return False End If Dim helperToken = endToken.GetNextToken(includeSkipped:=True) If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then Return False End If Dim asToken = helperToken.GetNextToken(includeSkipped:=True) If asToken.Kind <> SyntaxKind.AsKeyword Then Return False End If Return True End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/VisualBasic/Portable/BraceCompletion/InterpolatedStringBraceCompletionService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.BraceCompletion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery <Export(LanguageNames.VisualBasic, GetType(IBraceCompletionService)), [Shared]> Friend Class InterpolatedStringBraceCompletionService Inherits AbstractBraceCompletionService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New() End Sub Protected Overrides ReadOnly Property OpeningBrace As Char = DoubleQuote.OpenCharacter Protected Overrides ReadOnly Property ClosingBrace As Char = DoubleQuote.CloseCharacter Protected Overrides Function IsValidOpenBraceTokenAtPositionAsync(token As SyntaxToken, position As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean) Return Task.FromResult(IsValidOpeningBraceToken(token) AndAlso token.Span.End - 1 = position) End Function Public Overrides Function AllowOverTypeAsync(context As BraceCompletionContext, cancellationToken As CancellationToken) As Task(Of Boolean) Return AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken) End Function Public Overrides Async Function CanProvideBraceCompletionAsync(brace As Char, openingPosition As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean) Return OpeningBrace = brace And Await IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(False) End Function Protected Overrides Function IsValidOpeningBraceToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken) End Function Protected Overrides Function IsValidClosingBraceToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.DoubleQuoteToken) End Function Public Shared Async Function IsPositionInInterpolatedStringContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of Boolean) If position = 0 Then Return False End If Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) ' Position can be in an interpolated string if the preceding character is a $ Return text(position - 1) = "$"c End Function 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 System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.BraceCompletion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery <Export(LanguageNames.VisualBasic, GetType(IBraceCompletionService)), [Shared]> Friend Class InterpolatedStringBraceCompletionService Inherits AbstractBraceCompletionService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New() End Sub Protected Overrides ReadOnly Property OpeningBrace As Char = DoubleQuote.OpenCharacter Protected Overrides ReadOnly Property ClosingBrace As Char = DoubleQuote.CloseCharacter Protected Overrides Function IsValidOpenBraceTokenAtPositionAsync(token As SyntaxToken, position As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean) Return Task.FromResult(IsValidOpeningBraceToken(token) AndAlso token.Span.End - 1 = position) End Function Public Overrides Function AllowOverTypeAsync(context As BraceCompletionContext, cancellationToken As CancellationToken) As Task(Of Boolean) Return AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken) End Function Public Overrides Async Function CanProvideBraceCompletionAsync(brace As Char, openingPosition As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean) Return OpeningBrace = brace And Await IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(False) End Function Protected Overrides Function IsValidOpeningBraceToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken) End Function Protected Overrides Function IsValidClosingBraceToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.DoubleQuoteToken) End Function Public Shared Async Function IsPositionInInterpolatedStringContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of Boolean) If position = 0 Then Return False End If Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) ' Position can be in an interpolated string if the preceding character is a $ Return text(position - 1) = "$"c End Function End Class
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/TempPECompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(ITempPECompiler))] internal class TempPECompiler : ITempPECompiler { private readonly VisualStudioWorkspace _workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TempPECompiler(VisualStudioWorkspace workspace) => _workspace = workspace; public async Task<bool> CompileAsync(IWorkspaceProjectContext context, string outputFileName, ISet<string> filesToInclude, CancellationToken cancellationToken) { if (filesToInclude == null || filesToInclude.Count == 0) { throw new ArgumentException(nameof(filesToInclude), "Must specify some files to compile."); } if (outputFileName == null) { throw new ArgumentException(nameof(outputFileName), "Must specify an output file name."); } var project = _workspace.CurrentSolution.GetRequiredProject(context.Id); // Start by fetching the compilation we have already have that will have references correct var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); // Update to just the syntax trees we need to keep var syntaxTrees = new List<SyntaxTree>(capacity: filesToInclude.Count); foreach (var document in project.Documents) { if (document.FilePath != null && filesToInclude.Contains(document.FilePath)) { syntaxTrees.Add(await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } cancellationToken.ThrowIfCancellationRequested(); } compilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(syntaxTrees); // We need to inherit most of the projects options, mainly for VB (RootNamespace, GlobalImports etc.), but we need to override about some specific things surrounding the output compilation = compilation.WithOptions(compilation.Options // copied from the old TempPE compiler used by legacy, for parity. // See: https://github.com/dotnet/roslyn/blob/fab7134296816fc80019c60b0f5bef7400cf23ea/src/VisualStudio/CSharp/Impl/ProjectSystemShim/TempPECompilerService.cs#L58 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) // We always want to produce a debug, AnyCPU DLL .WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithPlatform(Platform.AnyCpu) .WithOptimizationLevel(OptimizationLevel.Debug) // Turn off any warnings as errors just in case .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress) .WithReportSuppressedDiagnostics(false) .WithSpecificDiagnosticOptions(null) // Turn off any signing and strong naming .WithDelaySign(false) .WithCryptoKeyFile(null) .WithPublicSign(false) .WithStrongNameProvider(null)); // AssemblyName should be set to the filename of the output file because multiple TempPE DLLs can be created for the same project compilation = compilation.WithAssemblyName(Path.GetFileName(outputFileName)); cancellationToken.ThrowIfCancellationRequested(); var outputPath = Path.GetDirectoryName(outputFileName); Directory.CreateDirectory(outputPath); using var file = FileUtilities.CreateFileStreamChecked(File.Create, outputFileName, nameof(outputFileName)); return compilation.Emit(file, cancellationToken: cancellationToken).Success; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(ITempPECompiler))] internal class TempPECompiler : ITempPECompiler { private readonly VisualStudioWorkspace _workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TempPECompiler(VisualStudioWorkspace workspace) => _workspace = workspace; public async Task<bool> CompileAsync(IWorkspaceProjectContext context, string outputFileName, ISet<string> filesToInclude, CancellationToken cancellationToken) { if (filesToInclude == null || filesToInclude.Count == 0) { throw new ArgumentException(nameof(filesToInclude), "Must specify some files to compile."); } if (outputFileName == null) { throw new ArgumentException(nameof(outputFileName), "Must specify an output file name."); } var project = _workspace.CurrentSolution.GetRequiredProject(context.Id); // Start by fetching the compilation we have already have that will have references correct var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); // Update to just the syntax trees we need to keep var syntaxTrees = new List<SyntaxTree>(capacity: filesToInclude.Count); foreach (var document in project.Documents) { if (document.FilePath != null && filesToInclude.Contains(document.FilePath)) { syntaxTrees.Add(await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } cancellationToken.ThrowIfCancellationRequested(); } compilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(syntaxTrees); // We need to inherit most of the projects options, mainly for VB (RootNamespace, GlobalImports etc.), but we need to override about some specific things surrounding the output compilation = compilation.WithOptions(compilation.Options // copied from the old TempPE compiler used by legacy, for parity. // See: https://github.com/dotnet/roslyn/blob/fab7134296816fc80019c60b0f5bef7400cf23ea/src/VisualStudio/CSharp/Impl/ProjectSystemShim/TempPECompilerService.cs#L58 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) // We always want to produce a debug, AnyCPU DLL .WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithPlatform(Platform.AnyCpu) .WithOptimizationLevel(OptimizationLevel.Debug) // Turn off any warnings as errors just in case .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress) .WithReportSuppressedDiagnostics(false) .WithSpecificDiagnosticOptions(null) // Turn off any signing and strong naming .WithDelaySign(false) .WithCryptoKeyFile(null) .WithPublicSign(false) .WithStrongNameProvider(null)); // AssemblyName should be set to the filename of the output file because multiple TempPE DLLs can be created for the same project compilation = compilation.WithAssemblyName(Path.GetFileName(outputFileName)); cancellationToken.ThrowIfCancellationRequested(); var outputPath = Path.GetDirectoryName(outputFileName); Directory.CreateDirectory(outputPath); using var file = FileUtilities.CreateFileStreamChecked(File.Create, outputFileName, nameof(outputFileName)); return compilation.Emit(file, cancellationToken: cancellationToken).Success; } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicPrimitiveFormatter.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.Globalization Imports Microsoft.CodeAnalysis.Scripting.Hosting Imports Microsoft.CodeAnalysis.Scripting.Hosting.ObjectFormatterHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting Friend Class VisualBasicPrimitiveFormatter Inherits CommonPrimitiveFormatter Protected Overrides ReadOnly Property NullLiteral As String Get Return "Nothing" End Get End Property Protected Overrides Function FormatLiteral(value As Boolean) As String Return ObjectDisplay.FormatLiteral(value) End Function Protected Overrides Function FormatLiteral(value As Date, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value) ' TODO (https://github.com/dotnet/roslyn/issues/8174): consume cultureInfo End Function Protected Overrides Function FormatLiteral(value As String, useQuotes As Boolean, escapeNonPrintable As Boolean, Optional numberRadix As Integer = NumberRadixDecimal) As String If escapeNonPrintable AndAlso Not useQuotes Then Throw New ArgumentException(VBScriptingResources.ExceptionEscapeWithoutQuote, NameOf(escapeNonPrintable)) End If Dim options As ObjectDisplayOptions = GetObjectDisplayOptions(useQuotes:=useQuotes, escapeNonPrintable:=escapeNonPrintable, numberRadix:=numberRadix) Return ObjectDisplay.FormatLiteral(value, options) End Function Protected Overrides Function FormatLiteral(c As Char, useQuotes As Boolean, escapeNonPrintable As Boolean, Optional includeCodePoints As Boolean = False, Optional numberRadix As Integer = NumberRadixDecimal) As String If escapeNonPrintable AndAlso Not useQuotes Then Throw New ArgumentException(VBScriptingResources.ExceptionEscapeWithoutQuote, NameOf(escapeNonPrintable)) End If Dim options As ObjectDisplayOptions = GetObjectDisplayOptions(useQuotes:=useQuotes, escapeNonPrintable:=escapeNonPrintable, includeCodePoints:=includeCodePoints, numberRadix:=numberRadix) Return ObjectDisplay.FormatLiteral(c, options) End Function Protected Overrides Function FormatLiteral(value As SByte, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Byte, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Short, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As UShort, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Integer, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As UInteger, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Long, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As ULong, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Double, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Single, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Decimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) 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.Globalization Imports Microsoft.CodeAnalysis.Scripting.Hosting Imports Microsoft.CodeAnalysis.Scripting.Hosting.ObjectFormatterHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting Friend Class VisualBasicPrimitiveFormatter Inherits CommonPrimitiveFormatter Protected Overrides ReadOnly Property NullLiteral As String Get Return "Nothing" End Get End Property Protected Overrides Function FormatLiteral(value As Boolean) As String Return ObjectDisplay.FormatLiteral(value) End Function Protected Overrides Function FormatLiteral(value As Date, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value) ' TODO (https://github.com/dotnet/roslyn/issues/8174): consume cultureInfo End Function Protected Overrides Function FormatLiteral(value As String, useQuotes As Boolean, escapeNonPrintable As Boolean, Optional numberRadix As Integer = NumberRadixDecimal) As String If escapeNonPrintable AndAlso Not useQuotes Then Throw New ArgumentException(VBScriptingResources.ExceptionEscapeWithoutQuote, NameOf(escapeNonPrintable)) End If Dim options As ObjectDisplayOptions = GetObjectDisplayOptions(useQuotes:=useQuotes, escapeNonPrintable:=escapeNonPrintable, numberRadix:=numberRadix) Return ObjectDisplay.FormatLiteral(value, options) End Function Protected Overrides Function FormatLiteral(c As Char, useQuotes As Boolean, escapeNonPrintable As Boolean, Optional includeCodePoints As Boolean = False, Optional numberRadix As Integer = NumberRadixDecimal) As String If escapeNonPrintable AndAlso Not useQuotes Then Throw New ArgumentException(VBScriptingResources.ExceptionEscapeWithoutQuote, NameOf(escapeNonPrintable)) End If Dim options As ObjectDisplayOptions = GetObjectDisplayOptions(useQuotes:=useQuotes, escapeNonPrintable:=escapeNonPrintable, includeCodePoints:=includeCodePoints, numberRadix:=numberRadix) Return ObjectDisplay.FormatLiteral(c, options) End Function Protected Overrides Function FormatLiteral(value As SByte, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Byte, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Short, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As UShort, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Integer, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As UInteger, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Long, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As ULong, Optional numberRadix As Integer = NumberRadixDecimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(numberRadix:=numberRadix), cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Double, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Single, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) End Function Protected Overrides Function FormatLiteral(value As Decimal, Optional cultureInfo As CultureInfo = Nothing) As String Return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None, cultureInfo) End Function End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/MetadataDefinitionItemEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation { public MetadataDefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket) : base(definitionBucket, context.Presenter) { } protected override object? GetValueWorker(string keyName) { switch (keyName) { case StandardTableKeyNames.Text: return DefinitionBucket.DefinitionItem.DisplayParts.JoinText(); } return null; } bool ISupportsNavigation.TryNavigateTo(bool isPreview, CancellationToken cancellationToken) => DefinitionBucket.DefinitionItem.TryNavigateTo( Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts .ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private class MetadataDefinitionItemEntry : AbstractItemEntry, ISupportsNavigation { public MetadataDefinitionItemEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket) : base(definitionBucket, context.Presenter) { } protected override object? GetValueWorker(string keyName) { switch (keyName) { case StandardTableKeyNames.Text: return DefinitionBucket.DefinitionItem.DisplayParts.JoinText(); } return null; } bool ISupportsNavigation.TryNavigateTo(bool isPreview, CancellationToken cancellationToken) => DefinitionBucket.DefinitionItem.TryNavigateTo( Presenter._workspace, showInPreviewTab: isPreview, activateTab: !isPreview, cancellationToken); // Only activate the tab if not opening in preview protected override IList<Inline> CreateLineTextInlines() => DefinitionBucket.DefinitionItem.DisplayParts .ToInlines(Presenter.ClassificationFormatMap, Presenter.TypeMap); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/CSharp/Portable/CodeGeneration/MethodGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/TestUtilities/Extensions/SolutionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public static class SolutionExtensions { public static Solution WithChangedOptionsFrom(this Solution solution, OptionSet optionSet) { var newOptions = solution.Options; foreach (var option in optionSet.GetChangedOptions(solution.Options)) { newOptions = newOptions.WithChangedOption(option, optionSet.GetOption(option)); } return solution.WithOptions(newOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public static class SolutionExtensions { public static Solution WithChangedOptionsFrom(this Solution solution, OptionSet optionSet) { var newOptions = solution.Options; foreach (var option in optionSet.GetChangedOptions(solution.Options)) { newOptions = newOptions.WithChangedOption(option, optionSet.GetOption(option)); } return solution.WithOptions(newOptions); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/MoveTypeTests.RenameFile.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.CodeRefactorings.MoveType Partial Public Class MoveTypeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function SingleClassInFileWithNoContainerNamespace_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class </File> Dim expectedDocumentName = "Class1.vb" Await TestRenameFileToMatchTypeAsync(code, expectedDocumentName) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_TypeNameMatchesFileName_RenameFile() As Task ' testworkspace creates files Like test1.cs, test2.cs And so on.. ' so type name matches filename here And rename file action should Not be offered. Dim code = <File> [||]Class test1 End Class </File> Await TestRenameFileToMatchTypeAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class Class test1 End Class </File> Await TestRenameFileToMatchTypeAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class Class Class2 End Class </File> Dim expectedDocumentName = "Class1.vb" Await TestRenameFileToMatchTypeAsync(code, expectedDocumentName) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Partial Public Class MoveTypeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function SingleClassInFileWithNoContainerNamespace_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class </File> Dim expectedDocumentName = "Class1.vb" Await TestRenameFileToMatchTypeAsync(code, expectedDocumentName) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_TypeNameMatchesFileName_RenameFile() As Task ' testworkspace creates files Like test1.cs, test2.cs And so on.. ' so type name matches filename here And rename file action should Not be offered. Dim code = <File> [||]Class test1 End Class </File> Await TestRenameFileToMatchTypeAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class Class test1 End Class </File> Await TestRenameFileToMatchTypeAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameFile() As Task Dim code = <File> [||]Class Class1 End Class Class Class2 End Class </File> Dim expectedDocumentName = "Class1.vb" Await TestRenameFileToMatchTypeAsync(code, expectedDocumentName) End Function End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/NameOfKeywordRecommenderTests.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.Expressions Public Class NameOfKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAtStartOfStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArgumentList_Position1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArgumentList_Position2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InVariableInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArrayInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArrayInitializerAfterCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterWhileTest() VerifyRecommendationsContain(<MethodBody>While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterCallTest() VerifyRecommendationsContain(<MethodBody>Call |</MethodBody>, "NameOf") 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.Expressions Public Class NameOfKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAtStartOfStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArgumentList_Position1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArgumentList_Position2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InVariableInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArrayInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InArrayInitializerAfterCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterWhileTest() VerifyRecommendationsContain(<MethodBody>While |</MethodBody>, "NameOf") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterCallTest() VerifyRecommendationsContain(<MethodBody>Call |</MethodBody>, "NameOf") End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedMember { internal abstract TEmbeddedTypesManager TypeManager { get; } } internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference where TMember : TSymbol, Cci.ITypeMemberReference { protected readonly TMember UnderlyingSymbol; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedMember(TMember underlyingSymbol) { this.UnderlyingSymbol = underlyingSymbol; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return null; } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics)); } } return builder.ToImmutableAndFree(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { throw ExceptionUtilities.Unreachable; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.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.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedMember { internal abstract TEmbeddedTypesManager TypeManager { get; } } internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference where TMember : TSymbol, Cci.ITypeMemberReference { protected readonly TMember UnderlyingSymbol; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedMember(TMember underlyingSymbol) { this.UnderlyingSymbol = underlyingSymbol; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return null; } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics)); } } return builder.ToImmutableAndFree(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { throw ExceptionUtilities.Unreachable; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Test/Utilities/VisualBasic/VBParser.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Text Imports System.Reflection Imports Microsoft.CodeAnalysis.Test.Utilities Public Class VBParser Private ReadOnly _options As VisualBasicParseOptions Public Sub New(Optional options As VisualBasicParseOptions = Nothing) _options = options End Sub Public Function Parse(code As String) As SyntaxTree Dim tree = VisualBasicSyntaxTree.ParseText(code, _options, "", Encoding.UTF8) Return tree End Function End Class 'TODO: We need this only temporarily until 893565 is fixed. Public Class VBKindProvider : Implements ISyntaxNodeKindProvider Public Function Kind(node As Object) As String Implements ISyntaxNodeKindProvider.Kind Return node.GetType().GetTypeInfo().GetDeclaredProperty("Kind").GetValue(node, Nothing).ToString() End Function 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 System.Text Imports System.Reflection Imports Microsoft.CodeAnalysis.Test.Utilities Public Class VBParser Private ReadOnly _options As VisualBasicParseOptions Public Sub New(Optional options As VisualBasicParseOptions = Nothing) _options = options End Sub Public Function Parse(code As String) As SyntaxTree Dim tree = VisualBasicSyntaxTree.ParseText(code, _options, "", Encoding.UTF8) Return tree End Function End Class 'TODO: We need this only temporarily until 893565 is fixed. Public Class VBKindProvider : Implements ISyntaxNodeKindProvider Public Function Kind(node As Object) As String Implements ISyntaxNodeKindProvider.Kind Return node.GetType().GetTypeInfo().GetDeclaredProperty("Kind").GetValue(node, Nothing).ToString() End Function End Class
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.Methods.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests_Methods : EditingTestBase { #region Methods [WorkItem(740443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740443")] [Fact] public void Method_Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" <AS:0>class C</AS:0> { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( active, diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "Goo(int a)")) }) }); } [Fact] public void Method_Body_Delete1() { var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }"; var src2 = "class C { <AS:0>extern int M();</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "extern int M()", FeaturesResources.method)); } [Fact] public void Method_ExpressionBody_Delete1() { var src1 = "class C { int M() => <AS:0>1</AS:0>; }"; var src2 = "class C { <AS:0>extern int M();</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "extern int M()", FeaturesResources.method)); } [Fact] public void Method_ExpressionBodyToBlockBody1() { var src1 = "class C { int M() => <AS:0>1</AS:0>; }"; var src2 = "class C { int M() <AS:0>{</AS:0> return 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Method_BlockBodyToExpressionBody1() { var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }"; var src2 = "class C { int M() => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } // Generics [Fact] public void Update_Inner_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { C c = new C(); int a = 5; int b = 10; <AS:1>c.Swap(ref a, ref b);</AS:1> } void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { C c = new C(); int a = 5; int b = 10; <AS:1>c.Swap(ref b, ref a);</AS:1> } } void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "c.Swap(ref b, ref a);")); } [Fact] public void Update_Inner_ParameterType_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Swap(5,6);</AS:1> } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Swap(null, null);</AS:1> } } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Swap(null, null);")); } [Fact] public void Update_Leaf_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Swap(5,6);</AS:1> } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Swap(5,6);</AS:1> } } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello world!"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericMethodUpdate, "static void Swap<T>(T lhs, T rhs)")); } // Async [WorkItem(749458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749458")] [Fact] public void Update_Leaf_AsyncMethod() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync().Result;</AS:1> } public async Task<string> WaitAsync() { <AS:0>await Task.Delay(1000);</AS:0> return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync().Result;</AS:1> } public async Task<string> WaitAsync() { <AS:0>await Task.Delay(100);</AS:0> return ""Done""; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Inner_AsyncMethod() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync(5).Result;</AS:1> } public async Task<string> WaitAsync(int millis) { <AS:0>await Task.Delay(millis);</AS:0> return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync(6).Result;</AS:1> } public async Task<string> WaitAsync(int millis) { <AS:0>await Task.Delay(millis);</AS:0> return ""Done""; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "string result = f.WaitAsync(6).Result;")); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Initializer_MultipleVariables1() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>int a = F()</AS:1>, b = G(); } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>int a = G()</AS:1>, b = F(); } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = G()")); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Initializer_MultipleVariables2() { var src1 = @" class Test { static void Main(string[] args) { int a = F(), <AS:1>b = G()</AS:1>; } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var src2 = @" class Test { static void Main(string[] args) { int a = G(), <AS:1>b = F()</AS:1>; } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F()")); } [Fact] public void MethodUpdateWithLocalVariables() { var src1 = @" class C { static void Main(string[] args) { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(a + b);</AS:0> } } "; var src2 = @" class C { static void Main(string[] args) { int <N:0.1>b = 2</N:0.1>; int <N:0.0>a = 1</N:0.0>; <AS:0>System.Console.WriteLine(a + b);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( active, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), syntaxMap[0]) }); } #endregion #region Constuctors [Fact] public void Constructor_ExpressionBodyToBlockBody1() { var src1 = "class C { int x; C() => <AS:0>x = 1</AS:0>; }"; var src2 = "class C { int x; <AS:0>C()</AS:0> { x = 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody1() { var src1 = "class C { int x; C() <AS:0>{</AS:0> x = 1; } }"; var src2 = "class C { int x; C() => <AS:0>x = 1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody2() { var src1 = "class C { int x; <AS:0>C()</AS:0> { x = 1; } }"; var src2 = "class C { int x; <AS:0>C()</AS:0> => x = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody3() { var src1 = "class C { int x; C() : <AS:0>base()</AS:0> { x = 1; } }"; var src2 = "class C { int x; <AS:0>C()</AS:0> => x = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Properties [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody3() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { set { } get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody_NonLeaf() { var src1 = @" class C { int P => <AS:1>M()</AS:1>; int M() { <AS:0>return 1;</AS:0> } } "; var src2 = @" class C { int P { get <AS:1>{</AS:1> return M(); } } int M() { <AS:0>return 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "get", FeaturesResources.code)); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int P => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { set { } get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int P => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void Property_BlockBodyToExpressionBody_NonLeaf() { var src1 = @" class C { int P { get { <AS:1>return M();</AS:1> } } int M() { <AS:0>return 1;</AS:0> } } "; var src2 = @" class C { int P => <AS:1>M()</AS:1>; int M() { <AS:0>return 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Can be improved with https://github.com/dotnet/roslyn/issues/22696 edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "int P", FeaturesResources.code)); } #endregion #region Indexers [Fact] public void Indexer_ExpressionBodyToBlockBody1() { var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_ExpressionBodyToBlockBody2() { var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_BlockBodyToExpressionBody1() { var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_BlockBodyToExpressionBody2() { var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } set { } } }"; var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact] public void Update_Leaf_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i+1] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set")); } [WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] [Fact] public void Update_Inner_Indexers1() { var src1 = @" using System; class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" using System; class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[1] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i+1] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Rude edits of active statements (AS:1) are not reported if the top-level edits are rude. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "stringCollection[1] = \"hello\";")); } [Fact] public void Update_Leaf_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[0];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get")); } [WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] [Fact] public void Update_Inner_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[1]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[0];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Rude edits of active statements (AS:1) are not reported if the top-level edits are rude. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(stringCollection[1]);")); } [Fact] public void Deleted_Leaf_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set")); } [Fact] public void Deleted_Inner_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Deleted_Leaf_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>}</AS:0> set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get")); } [Fact] public void Deleted_Inner_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>}</AS:1> } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } #endregion #region Operators [Fact] public void Operator_ExpressionBodyToBlockBody1() { var src1 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }"; var src2 = "class C { public static C operator +(C t1, C t2) <AS:0>{</AS:0> return null; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_ExpressionBodyToBlockBody2() { var src1 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }"; var src2 = "class C { public static explicit operator D(C t) <AS:0>{</AS:0> return null; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_BlockBodyToExpressionBody1() { var src1 = "class C { public static C operator +(C t1, C t2) { <AS:0>return null;</AS:0> } }"; var src2 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_BlockBodyToExpressionBody2() { var src1 = "class C { public static explicit operator D(C t) { <AS:0>return null;</AS:0> } }"; var src2 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] [Fact] public void Update_Leaf_OverloadedOperator() { var src1 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + 2 * t2.a);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] [Fact] public void Update_Inner_OverloadedOperator() { var src1 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } public static Test operator *(Test t1, Test t2) { return new Test(t1.a * t2.a); } }"; var src2 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 * t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } public static Test operator *(Test t1, Test t2) { return new Test(t1.a * t2.a); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Test t3 = t1 * t2;")); } #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.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests_Methods : EditingTestBase { #region Methods [WorkItem(740443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740443")] [Fact] public void Method_Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" <AS:0>class C</AS:0> { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( active, diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "Goo(int a)")) }) }); } [Fact] public void Method_Body_Delete1() { var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }"; var src2 = "class C { <AS:0>extern int M();</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "extern int M()", FeaturesResources.method)); } [Fact] public void Method_ExpressionBody_Delete1() { var src1 = "class C { int M() => <AS:0>1</AS:0>; }"; var src2 = "class C { <AS:0>extern int M();</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "extern int M()", FeaturesResources.method)); } [Fact] public void Method_ExpressionBodyToBlockBody1() { var src1 = "class C { int M() => <AS:0>1</AS:0>; }"; var src2 = "class C { int M() <AS:0>{</AS:0> return 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Method_BlockBodyToExpressionBody1() { var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }"; var src2 = "class C { int M() => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } // Generics [Fact] public void Update_Inner_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { C c = new C(); int a = 5; int b = 10; <AS:1>c.Swap(ref a, ref b);</AS:1> } void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { C c = new C(); int a = 5; int b = 10; <AS:1>c.Swap(ref b, ref a);</AS:1> } } void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "c.Swap(ref b, ref a);")); } [Fact] public void Update_Inner_ParameterType_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Swap(5,6);</AS:1> } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Swap(null, null);</AS:1> } } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Swap(null, null);")); } [Fact] public void Update_Leaf_GenericMethod() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Swap(5,6);</AS:1> } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello"");</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Swap(5,6);</AS:1> } } static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T> { <AS:0>Console.WriteLine(""hello world!"");</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericMethodUpdate, "static void Swap<T>(T lhs, T rhs)")); } // Async [WorkItem(749458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749458")] [Fact] public void Update_Leaf_AsyncMethod() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync().Result;</AS:1> } public async Task<string> WaitAsync() { <AS:0>await Task.Delay(1000);</AS:0> return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync().Result;</AS:1> } public async Task<string> WaitAsync() { <AS:0>await Task.Delay(100);</AS:0> return ""Done""; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Inner_AsyncMethod() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync(5).Result;</AS:1> } public async Task<string> WaitAsync(int millis) { <AS:0>await Task.Delay(millis);</AS:0> return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); <AS:1>string result = f.WaitAsync(6).Result;</AS:1> } public async Task<string> WaitAsync(int millis) { <AS:0>await Task.Delay(millis);</AS:0> return ""Done""; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "string result = f.WaitAsync(6).Result;")); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Initializer_MultipleVariables1() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>int a = F()</AS:1>, b = G(); } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>int a = G()</AS:1>, b = F(); } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = G()")); } [WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")] [Fact] public void Update_Initializer_MultipleVariables2() { var src1 = @" class Test { static void Main(string[] args) { int a = F(), <AS:1>b = G()</AS:1>; } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var src2 = @" class Test { static void Main(string[] args) { int a = G(), <AS:1>b = F()</AS:1>; } public int F() { <AS:0>return 1;</AS:0> } public int G() { return 2; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F()")); } [Fact] public void MethodUpdateWithLocalVariables() { var src1 = @" class C { static void Main(string[] args) { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(a + b);</AS:0> } } "; var src2 = @" class C { static void Main(string[] args) { int <N:0.1>b = 2</N:0.1>; int <N:0.0>a = 1</N:0.0>; <AS:0>System.Console.WriteLine(a + b);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( active, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), syntaxMap[0]) }); } #endregion #region Constuctors [Fact] public void Constructor_ExpressionBodyToBlockBody1() { var src1 = "class C { int x; C() => <AS:0>x = 1</AS:0>; }"; var src2 = "class C { int x; <AS:0>C()</AS:0> { x = 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody1() { var src1 = "class C { int x; C() <AS:0>{</AS:0> x = 1; } }"; var src2 = "class C { int x; C() => <AS:0>x = 1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody2() { var src1 = "class C { int x; <AS:0>C()</AS:0> { x = 1; } }"; var src2 = "class C { int x; <AS:0>C()</AS:0> => x = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Constructor_BlockBodyToExpressionBody3() { var src1 = "class C { int x; C() : <AS:0>base()</AS:0> { x = 1; } }"; var src2 = "class C { int x; <AS:0>C()</AS:0> => x = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Properties [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody3() { var src1 = "class C { int P => <AS:0>1</AS:0>; }"; var src2 = "class C { int P { set { } get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_ExpressionBodyToBlockBody_NonLeaf() { var src1 = @" class C { int P => <AS:1>M()</AS:1>; int M() { <AS:0>return 1;</AS:0> } } "; var src2 = @" class C { int P { get <AS:1>{</AS:1> return M(); } } int M() { <AS:0>return 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "get", FeaturesResources.code)); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int P => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { set { } get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int P => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void Property_BlockBodyToExpressionBody_NonLeaf() { var src1 = @" class C { int P { get { <AS:1>return M();</AS:1> } } int M() { <AS:0>return 1;</AS:0> } } "; var src2 = @" class C { int P => <AS:1>M()</AS:1>; int M() { <AS:0>return 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Can be improved with https://github.com/dotnet/roslyn/issues/22696 edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "int P", FeaturesResources.code)); } #endregion #region Indexers [Fact] public void Indexer_ExpressionBodyToBlockBody1() { var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_ExpressionBodyToBlockBody2() { var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_BlockBodyToExpressionBody1() { var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } } }"; var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Indexer_BlockBodyToExpressionBody2() { var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } set { } } }"; var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact] public void Update_Leaf_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i+1] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set")); } [WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] [Fact] public void Update_Inner_Indexers1() { var src1 = @" using System; class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" using System; class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[1] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i+1] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Rude edits of active statements (AS:1) are not reported if the top-level edits are rude. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "stringCollection[1] = \"hello\";")); } [Fact] public void Update_Leaf_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[0];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get")); } [WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")] [Fact] public void Update_Inner_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[1]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[0];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Rude edits of active statements (AS:1) are not reported if the top-level edits are rude. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(stringCollection[1]);")); } [Fact] public void Deleted_Leaf_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "set")); } [Fact] public void Deleted_Inner_Indexers1() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>stringCollection[0] = ""hello"";</AS:1> Console.WriteLine(stringCollection[0]); } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { <AS:0>arr[i] = value;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Deleted_Leaf_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>}</AS:0> set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.GenericTypeUpdate, "get")); } [Fact] public void Deleted_Inner_Indexers2() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>Console.WriteLine(stringCollection[0]);</AS:1> } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; <AS:1>}</AS:1> } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { <AS:0>return arr[i];</AS:0> } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } #endregion #region Operators [Fact] public void Operator_ExpressionBodyToBlockBody1() { var src1 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }"; var src2 = "class C { public static C operator +(C t1, C t2) <AS:0>{</AS:0> return null; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_ExpressionBodyToBlockBody2() { var src1 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }"; var src2 = "class C { public static explicit operator D(C t) <AS:0>{</AS:0> return null; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_BlockBodyToExpressionBody1() { var src1 = "class C { public static C operator +(C t1, C t2) { <AS:0>return null;</AS:0> } }"; var src2 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Operator_BlockBodyToExpressionBody2() { var src1 = "class C { public static explicit operator D(C t) { <AS:0>return null;</AS:0> } }"; var src2 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] [Fact] public void Update_Leaf_OverloadedOperator() { var src1 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + 2 * t2.a);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")] [Fact] public void Update_Inner_OverloadedOperator() { var src1 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 + t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } public static Test operator *(Test t1, Test t2) { return new Test(t1.a * t2.a); } }"; var src2 = @" class Test { static void Main(string[] args) { Test t1 = new Test(5); Test t2 = new Test(5); <AS:1>Test t3 = t1 * t2;</AS:1> } public static Test operator +(Test t1, Test t2) { <AS:0>return new Test(t1.a + t2.a);</AS:0> } public static Test operator *(Test t1, Test t2) { return new Test(t1.a * t2.a); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Test t3 = t1 * t2;")); } #endregion } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Dependencies/Collections/Internal/RoslynUnsafe.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static unsafe class RoslynUnsafe { /// <summary> /// Returns a by-ref to type <typeparamref name="T"/> that is a null reference. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T NullRef<T>() => ref Unsafe.AsRef<T>(null); /// <summary> /// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference. /// </summary> /// <remarks> /// This check is conceptually similar to <c>(void*)(&amp;source) == nullptr</c>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullRef<T>(ref T source) => Unsafe.AsPointer(ref source) == 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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static unsafe class RoslynUnsafe { /// <summary> /// Returns a by-ref to type <typeparamref name="T"/> that is a null reference. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T NullRef<T>() => ref Unsafe.AsRef<T>(null); /// <summary> /// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference. /// </summary> /// <remarks> /// This check is conceptually similar to <c>(void*)(&amp;source) == nullptr</c>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullRef<T>(ref T source) => Unsafe.AsPointer(ref source) == null; } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests Inherits SemanticModelTestBase #Region "LookupSymbols Function" <Fact()> Public Sub LookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class B Public f1 as Integer End Class Class D Inherits B Public Sub goo() Console.WriteLine() 'BIND:"WriteLine" End Sub End Class Module M Public f1 As Integer Public f2 As Integer End Module Module M2 Public f1 As Integer Public f2 As Integer End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") Dim syms = semanticModel.LookupSymbols(pos, Nothing, "f1") Assert.Equal(1, syms.Length) Assert.Equal("B.f1 As System.Int32", syms(0).ToTestDisplayString()) ' This one is tricky.. M.f2 and M2.f2 are ambiguous at the same ' binding scope, so we get both symbols here. syms = semanticModel.LookupSymbols(pos, Nothing, "f2") Assert.Equal(2, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("M.f2 As System.Int32", fullNames(0)) Assert.Equal("M2.f2 As System.Int32", fullNames(1)) syms = semanticModel.LookupSymbols(pos, Nothing, "int32") Assert.Equal(1, syms.Length) Assert.Equal("System.Int32", syms(0).ToTestDisplayString()) CompilationUtils.AssertNoErrors(compilation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class B End Class Class A Class B(Of X) End Class Class B(Of X, Y) End Class Sub M() Dim B As Integer Console.WriteLine() End Sub End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInside As Integer = CompilationUtils.FindPositionFromText(tree, "WriteLine") Dim posOutside As Integer = CompilationUtils.FindPositionFromText(tree, "Sub M") ' Inside the method, "B" shadows classes of any arity. Dim syms = semanticModel.LookupSymbols(posInside, Nothing, "b", Nothing) Assert.Equal(1, syms.Length) Assert.Equal("B As System.Int32", syms(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Local, syms(0).Kind) ' Outside the method, all B's are available. syms = semanticModel.LookupSymbols(posOutside, Nothing, "b", Nothing) Assert.Equal(3, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) ' Inside the method, all B's are available if only types/namespace are allowed syms = semanticModel.LookupNamespacesAndTypes(posOutside, Nothing, "b") Assert.Equal(3, syms.Length) fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports AliasZ = B.Z Class A Public Class Z(Of X) End Class Public Class Z(Of X, Y) End Class End Class Class B Inherits A Public Class Z ' in B End Class Public Class Z(Of X) End Class End Class Class C Inherits B Public z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") ' Lookup Z, all arities, inside B Dim syms = semanticModel.LookupSymbols(posInsideB, name:="z") ' Assert.Equal(3, syms.Count) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.Z(Of X, Y)", fullNames(0)) Assert.Equal("B.Z", fullNames(1)) Assert.Equal("B.Z(Of X)", fullNames(2)) ' Lookup Z, all arities, inside C. Since fields shadow by name in VB, only the field is found. syms = semanticModel.LookupSymbols(posInsideC, name:="z") Assert.Equal(1, syms.Length) Assert.Equal("C.z As System.Int32", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz") Assert.Equal(1, syms.Length) Assert.Equal("AliasZ=B.Z", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C with container syms = semanticModel.LookupSymbols(posInsideC, name:="C") Assert.Equal(1, syms.Length) Assert.Equal("C", syms(0).ToTestDisplayString()) Dim C = DirectCast(syms.Single, NamespaceOrTypeSymbol) syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz", container:=C) Assert.Equal(0, syms.Length) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup all symbols Dim syms = From s In semanticModel.LookupSymbols(posInsideM, name:=Nothing) Dim fullNames = From s In syms Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Contains("N1.N2.A", fullNames) Assert.Contains("N1.N2.B", fullNames) Assert.Contains("N1.N2.C", fullNames) Assert.Contains("N1.N2.C.Z As System.Int32", fullNames) Assert.Contains("Sub N1.N2.C.M()", fullNames) Assert.Contains("N1", fullNames) Assert.Contains("N1.N2", fullNames) Assert.Contains("System", fullNames) Assert.Contains("Microsoft", fullNames) Assert.Contains("Function System.Object.ToString() As System.String", fullNames) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsMustNotBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Public X As Integer Public Shared SX As Integer End Class Class B Inherits A Public Function Y() As Integer End Function Public Shared Function SY() As Integer End Function End Class Class C Inherits B Public Z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim classC As NamedTypeSymbol = DirectCast(compilation.GlobalNamespace().GetMembers("C").Single(), NamedTypeSymbol) Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") Dim symbols = semanticModel.LookupStaticMembers(position:=posInsideC, container:=classC, name:=Nothing) Dim fullNames = From s In symbols.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal(4, symbols.Length) Assert.Equal("A.SX As System.Int32", fullNames(0)) Assert.Equal("Function B.SY() As System.Int32", fullNames(1)) Assert.Equal("Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(2)) Assert.Equal("Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(3)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsInTypeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Interface IA Sub MA() End Interface Interface IB Sub MB() End Interface Interface IC Sub M(Of T, U)() End Interface Class C Implements IA Private Sub MA() Implements IA.MA End Sub Public Sub M(Of T)() End Sub End Class Class D(Of T As IB) Public Sub MD(Of U As {C, T, IC}, V As Structure)(_u As U, _v As V) End Sub End Class Module E <Extension()> Friend Sub [ME](c As IC, o As Object) End Sub <Extension()> Friend Sub [ME](v As System.ValueType) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim method = compilation.GlobalNamespace().GetMember(Of NamedTypeSymbol)("D").GetMember(Of MethodSymbol)("MD") Dim parameter = method.Parameters(0) Dim position = CompilationUtils.FindPositionFromText(tree, "As U") Dim symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub C.M(Of T)()", "Function Object.ToString() As String", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetHashCode() As Integer", "Function Object.GetType() As Type", "Sub IB.MB()", "Sub IC.ME(o As Object)") parameter = method.Parameters(1) position = CompilationUtils.FindPositionFromText(tree, "As V") symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Function ValueType.Equals(obj As Object) As Boolean", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function ValueType.GetHashCode() As Integer", "Function Object.GetHashCode() As Integer", "Function ValueType.ToString() As String", "Function Object.ToString() As String", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetType() As Type", "Sub ValueType.ME()") CompilationUtils.AssertNoErrors(compilation) End Sub Private Shared Sub CheckSymbols(symbols As ImmutableArray(Of ISymbol), ParamArray descriptions As String()) CompilationUtils.CheckSymbols(symbols, descriptions) End Sub <Fact()> Public Sub LookupNames1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideM) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.Contains("Z", names) Assert.Contains("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.Contains("ToString", names) Assert.Contains("Equals", names) Assert.Contains("GetType", names) ' Lookup names, namespace and types only names = From n In semanticModel.LookupNames(posInsideM, namespacesAndTypesOnly:=True) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.DoesNotContain("Z", names) Assert.DoesNotContain("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.DoesNotContain("ToString", names) Assert.DoesNotContain("Equals", names) Assert.DoesNotContain("GetType", names) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Inherits B Public X As Integer End Class Class B Inherits A Public Y As Integer ' in B End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </expected>) ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideB) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("X", names) Assert.Contains("Y", names) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(System.IDisposable.Equals(1, 1)) Dim x As I1 = New C1() System.Console.WriteLine(x.GetHashCode()) 'BIND:"GetHashCode" End Sub End Module Interface I1 End Interface Class C1 Implements I1 Public Overrides Function GetHashCode() As Integer Return 1234 End Function End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ True 1234 ]]>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"), name:="GetHashCode") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function System.Object.GetHashCode() As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) Dim getHashCode = DirectCast(actual_lookupSymbols(0), MethodSymbol) Assert.Contains(getHashCode, GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"))) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As I1 = Nothing x.GetHashCode() x.GetHashCode(1) x.ToString() x.ToString(1) x.ToString(1, 2) Dim y As I5 = Nothing y.GetHashCode() End Sub &lt;Extension()&gt; Function ToString(this As I1, x As Integer, y As Integer) As String Return Nothing End Function End Module Interface I1 Function GetHashCode(x As Integer) As Integer Function ToString(x As Integer) As Integer End Interface Interface I3 Function GetHashCode(x As Integer) As Integer End Interface Interface I4 Function GetHashCode() As Integer End Interface Interface I5 Inherits I3, I4 End Interface Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <result> BC30455: Argument not specified for parameter 'x' of 'Function GetHashCode(x As Integer) As Integer'. x.GetHashCode() ~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. x.ToString() ~~~~~~~~ </result> ) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClass"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMeNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() Me.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() MyClass.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNoInstance"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub C() End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub B1..ctor(x As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("B1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfInaccessibleOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub B1..ctor(x As System.Int32)", "Sub B1..ctor(x As System.String)" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("MyBase", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim baseType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B1") Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim result = LookupResult.GetInstance() binder.LookupMember(result, baseType, "Finalize", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Sub System.Object.Finalize()", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.LookupMember(result, baseType, "MemberwiseClone", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function System.Object.MemberwiseClone() As System.Object", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub #End Region #Region "Regression" <WorkItem(539107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539107")> <Fact()> Public Sub LookupAtLocationEndSubNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 End Sub 'BIND:"End Sub" End Class </file> </compilation>) Dim expected_in_lookupNames = { "count", "param1" } Dim expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539114")> <Fact()> Public Sub LookupAtLocationSubBlockNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) 'BIND:"Public Sub Method1(ByVal param1 As Integer)" Dim count As Integer = 45 End Sub End Class </file> </compilation>) Dim not_expected_in_lookupNames = { "count", "param1" } Dim not_expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539119")> <Fact()> Public Sub LookupSymbolsByNameIncorrectArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 'BIND:"45" End Sub End Class </file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="count", arity:=1) Assert.Empty(actual_lookupSymbols) End Sub <WorkItem(539130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539130")> <Fact()> Public Sub LookupWithNameZeroArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Method1(Of T)(i As T) End Sub Sub Method1(Of T, U)(i As T, j As U) End Sub Sub Method1(i As Integer) End Sub Sub Method1(i As Integer, j As Integer) End Sub Public Sub Main() Dim x As Integer = 45 'BIND:"45" End Sub End Module </file> </compilation>) Dim expected_in_lookupSymbols = { "Sub Module1.Method1(i As System.Int32)", "Sub Module1.Method1(i As System.Int32, j As System.Int32)" } Dim not_expected_in_lookupSymbols = { "Sub Module1.Method1(Of T)(i As T)", "Sub Module1.Method1(Of T, U)(i As T, j As U)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Method1", arity:=0) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(5004, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LookupExcludeInAppropriateNS() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 End Module </file> </compilation>, {SystemDataRef}) Dim not_expected_in_lookup = { "<CrtImplementationDetails>", "<CppImplementationDetails>" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Const position = 0 Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim actual_lookupSymbols = model.LookupSymbols(position) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookup(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookup(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunctionIgnoreReturnVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" Return 10 End Function End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("Dim", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim result = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing binder.Lookup(result, "Func1", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function Test.Func1() As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.Lookup(result, "x", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("x As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" 'BIND:"10" Return 10 End Function End Class </file> </compilation>) Dim expected_in_lookupNames = { "Func1", "x" } Dim expected_in_lookupSymbols = { "Func1 As System.Int32", "x As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527759")> <Fact()> Public Sub LookupAtLocationClassTypeBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527760")> <Fact()> Public Sub LookupAtLocationClassTypeStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527761")> <Fact()> Public Sub LookupAtLocationEndClassStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class 'BIND:"End Class" </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(539175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539175")> <Fact()> Public Sub LookupAtLocationNamespaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 'BIND:"Namespace NS1" Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS3" } Dim not_expected_in_lookupNames = { "NS2", "T1", "T2", "T3" } Dim expected_in_lookupSymbols = { "NS1", "NS3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2", "NS1.NS2.T1", "NS1.T2", "NS1.T3" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539177")> <Fact()> Public Sub LookupAtLocationEndNamespaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace 'BIND:"End Namespace" Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS2", "NS3", "T2", "T3" } Dim not_expected_in_lookupNames = { "T1" } Dim expected_in_lookupSymbols = { "NS1", "NS3", "NS1.NS2", "NS1.T2", "NS1.T3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2.T1" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) For Each expectedName In expected_in_lookupNames Assert.Contains(expectedName, actual_lookupNames) Next For Each notExpectedName In not_expected_in_lookupNames Assert.DoesNotContain(notExpectedName, actual_lookupNames) Next For Each expectedName In expected_in_lookupSymbols Assert.Contains(expectedName, actual_lookupSymbols_as_string) Next For Each notExpectedName In not_expected_in_lookupSymbols Assert.DoesNotContain(notExpectedName, actual_lookupSymbols_as_string) Next End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact()> Public Sub LookupAtLocationInterfaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationEndInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub sub1(ByVal i As Integer) End Interface 'BIND:"End Interface" </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527774")> <Fact()> Public Sub LookupAtLocationCompilationUnitSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Imports A1 = System 'BIND:"Imports A1 = System" </file> </compilation>) Dim expected_in_lookupNames = { "System", "Microsoft" } Dim expected_in_lookupSymbols = { "System", "Microsoft" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Equal(2, actual_lookupNames.Count) Assert.Equal(2, actual_lookupSymbols_as_string.Count) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527779")> <Fact()> Public Sub LookupAtLocationInheritsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Public Class C1 Public Sub C1Sub1() End Sub End Class Public Class C2 Inherits C1 'BIND:"Inherits C1" Public Sub C2Sub1() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "C1", "C2", "C2Sub1" } Dim not_expected_in_lookupNames = { "C1Sub1" } Dim expected_in_lookupSymbols = { "C1", "C2", "Sub C2.C2Sub1()" } Dim not_expected_in_lookupSymbols = { "Sub C1.C1Sub1()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(527780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527780")> <Fact()> Public Sub LookupAtLocationImplementsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub Sub1() End Interface Public Class ImplementationClass1 Implements Interface1 'BIND:"Implements Interface1" Sub Sub1() Implements Interface1.Sub1 End Sub Sub Sub2() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "ImplementationClass1", "Sub1", "Sub2" } Dim expected_in_lookupSymbols = { "Interface1", "ImplementationClass1", "Sub ImplementationClass1.Sub1()", "Sub ImplementationClass1.Sub2()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539232")> <Fact()> Public Sub LookupAtLocationInsideIfPartOfSingleLineIfStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me1 As Integer = 10" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me1" } Dim not_expected_in_lookupNames = { "me2" } Dim expected_in_lookupSymbols = { "me1 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me2 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(539234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539234")> <Fact()> Public Sub LookupAtLocationInsideElsePartOfSingleLineElseStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me2 As Integer = 20" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me2" } Dim not_expected_in_lookupNames = { "me1" } Dim expected_in_lookupSymbols = { "me2 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(542856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542856")> <Fact()> Public Sub LookupParamSingleLineLambdaExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub Bug10272_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Function End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub LookupSymbolsAtEOF() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim eof = tree.GetCompilationUnitRoot().FullSpan.End Assert.NotEqual(eof, 0) Dim symbols = model.LookupSymbols(eof) CompilationUtils.CheckSymbols(symbols, "Microsoft", "C", "System") End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 If True Then Dim y = 1 x=y 'BIND:"y" End If End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 Select Case 1 Case 1 Dim y = 1 x=y 'BIND:"y" End Select End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests Inherits SemanticModelTestBase #Region "LookupSymbols Function" <Fact()> Public Sub LookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class B Public f1 as Integer End Class Class D Inherits B Public Sub goo() Console.WriteLine() 'BIND:"WriteLine" End Sub End Class Module M Public f1 As Integer Public f2 As Integer End Module Module M2 Public f1 As Integer Public f2 As Integer End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") Dim syms = semanticModel.LookupSymbols(pos, Nothing, "f1") Assert.Equal(1, syms.Length) Assert.Equal("B.f1 As System.Int32", syms(0).ToTestDisplayString()) ' This one is tricky.. M.f2 and M2.f2 are ambiguous at the same ' binding scope, so we get both symbols here. syms = semanticModel.LookupSymbols(pos, Nothing, "f2") Assert.Equal(2, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("M.f2 As System.Int32", fullNames(0)) Assert.Equal("M2.f2 As System.Int32", fullNames(1)) syms = semanticModel.LookupSymbols(pos, Nothing, "int32") Assert.Equal(1, syms.Length) Assert.Equal("System.Int32", syms(0).ToTestDisplayString()) CompilationUtils.AssertNoErrors(compilation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class B End Class Class A Class B(Of X) End Class Class B(Of X, Y) End Class Sub M() Dim B As Integer Console.WriteLine() End Sub End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInside As Integer = CompilationUtils.FindPositionFromText(tree, "WriteLine") Dim posOutside As Integer = CompilationUtils.FindPositionFromText(tree, "Sub M") ' Inside the method, "B" shadows classes of any arity. Dim syms = semanticModel.LookupSymbols(posInside, Nothing, "b", Nothing) Assert.Equal(1, syms.Length) Assert.Equal("B As System.Int32", syms(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Local, syms(0).Kind) ' Outside the method, all B's are available. syms = semanticModel.LookupSymbols(posOutside, Nothing, "b", Nothing) Assert.Equal(3, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) ' Inside the method, all B's are available if only types/namespace are allowed syms = semanticModel.LookupNamespacesAndTypes(posOutside, Nothing, "b") Assert.Equal(3, syms.Length) fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports AliasZ = B.Z Class A Public Class Z(Of X) End Class Public Class Z(Of X, Y) End Class End Class Class B Inherits A Public Class Z ' in B End Class Public Class Z(Of X) End Class End Class Class C Inherits B Public z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") ' Lookup Z, all arities, inside B Dim syms = semanticModel.LookupSymbols(posInsideB, name:="z") ' Assert.Equal(3, syms.Count) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.Z(Of X, Y)", fullNames(0)) Assert.Equal("B.Z", fullNames(1)) Assert.Equal("B.Z(Of X)", fullNames(2)) ' Lookup Z, all arities, inside C. Since fields shadow by name in VB, only the field is found. syms = semanticModel.LookupSymbols(posInsideC, name:="z") Assert.Equal(1, syms.Length) Assert.Equal("C.z As System.Int32", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz") Assert.Equal(1, syms.Length) Assert.Equal("AliasZ=B.Z", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C with container syms = semanticModel.LookupSymbols(posInsideC, name:="C") Assert.Equal(1, syms.Length) Assert.Equal("C", syms(0).ToTestDisplayString()) Dim C = DirectCast(syms.Single, NamespaceOrTypeSymbol) syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz", container:=C) Assert.Equal(0, syms.Length) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup all symbols Dim syms = From s In semanticModel.LookupSymbols(posInsideM, name:=Nothing) Dim fullNames = From s In syms Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Contains("N1.N2.A", fullNames) Assert.Contains("N1.N2.B", fullNames) Assert.Contains("N1.N2.C", fullNames) Assert.Contains("N1.N2.C.Z As System.Int32", fullNames) Assert.Contains("Sub N1.N2.C.M()", fullNames) Assert.Contains("N1", fullNames) Assert.Contains("N1.N2", fullNames) Assert.Contains("System", fullNames) Assert.Contains("Microsoft", fullNames) Assert.Contains("Function System.Object.ToString() As System.String", fullNames) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsMustNotBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Public X As Integer Public Shared SX As Integer End Class Class B Inherits A Public Function Y() As Integer End Function Public Shared Function SY() As Integer End Function End Class Class C Inherits B Public Z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim classC As NamedTypeSymbol = DirectCast(compilation.GlobalNamespace().GetMembers("C").Single(), NamedTypeSymbol) Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") Dim symbols = semanticModel.LookupStaticMembers(position:=posInsideC, container:=classC, name:=Nothing) Dim fullNames = From s In symbols.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal(4, symbols.Length) Assert.Equal("A.SX As System.Int32", fullNames(0)) Assert.Equal("Function B.SY() As System.Int32", fullNames(1)) Assert.Equal("Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(2)) Assert.Equal("Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(3)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsInTypeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Interface IA Sub MA() End Interface Interface IB Sub MB() End Interface Interface IC Sub M(Of T, U)() End Interface Class C Implements IA Private Sub MA() Implements IA.MA End Sub Public Sub M(Of T)() End Sub End Class Class D(Of T As IB) Public Sub MD(Of U As {C, T, IC}, V As Structure)(_u As U, _v As V) End Sub End Class Module E <Extension()> Friend Sub [ME](c As IC, o As Object) End Sub <Extension()> Friend Sub [ME](v As System.ValueType) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim method = compilation.GlobalNamespace().GetMember(Of NamedTypeSymbol)("D").GetMember(Of MethodSymbol)("MD") Dim parameter = method.Parameters(0) Dim position = CompilationUtils.FindPositionFromText(tree, "As U") Dim symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub C.M(Of T)()", "Function Object.ToString() As String", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetHashCode() As Integer", "Function Object.GetType() As Type", "Sub IB.MB()", "Sub IC.ME(o As Object)") parameter = method.Parameters(1) position = CompilationUtils.FindPositionFromText(tree, "As V") symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Function ValueType.Equals(obj As Object) As Boolean", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function ValueType.GetHashCode() As Integer", "Function Object.GetHashCode() As Integer", "Function ValueType.ToString() As String", "Function Object.ToString() As String", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetType() As Type", "Sub ValueType.ME()") CompilationUtils.AssertNoErrors(compilation) End Sub Private Shared Sub CheckSymbols(symbols As ImmutableArray(Of ISymbol), ParamArray descriptions As String()) CompilationUtils.CheckSymbols(symbols, descriptions) End Sub <Fact()> Public Sub LookupNames1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideM) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.Contains("Z", names) Assert.Contains("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.Contains("ToString", names) Assert.Contains("Equals", names) Assert.Contains("GetType", names) ' Lookup names, namespace and types only names = From n In semanticModel.LookupNames(posInsideM, namespacesAndTypesOnly:=True) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.DoesNotContain("Z", names) Assert.DoesNotContain("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.DoesNotContain("ToString", names) Assert.DoesNotContain("Equals", names) Assert.DoesNotContain("GetType", names) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Inherits B Public X As Integer End Class Class B Inherits A Public Y As Integer ' in B End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </expected>) ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideB) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("X", names) Assert.Contains("Y", names) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(System.IDisposable.Equals(1, 1)) Dim x As I1 = New C1() System.Console.WriteLine(x.GetHashCode()) 'BIND:"GetHashCode" End Sub End Module Interface I1 End Interface Class C1 Implements I1 Public Overrides Function GetHashCode() As Integer Return 1234 End Function End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ True 1234 ]]>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"), name:="GetHashCode") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function System.Object.GetHashCode() As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) Dim getHashCode = DirectCast(actual_lookupSymbols(0), MethodSymbol) Assert.Contains(getHashCode, GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"))) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As I1 = Nothing x.GetHashCode() x.GetHashCode(1) x.ToString() x.ToString(1) x.ToString(1, 2) Dim y As I5 = Nothing y.GetHashCode() End Sub &lt;Extension()&gt; Function ToString(this As I1, x As Integer, y As Integer) As String Return Nothing End Function End Module Interface I1 Function GetHashCode(x As Integer) As Integer Function ToString(x As Integer) As Integer End Interface Interface I3 Function GetHashCode(x As Integer) As Integer End Interface Interface I4 Function GetHashCode() As Integer End Interface Interface I5 Inherits I3, I4 End Interface Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <result> BC30455: Argument not specified for parameter 'x' of 'Function GetHashCode(x As Integer) As Integer'. x.GetHashCode() ~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. x.ToString() ~~~~~~~~ </result> ) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClass"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMeNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() Me.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() MyClass.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNoInstance"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub C() End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub B1..ctor(x As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("B1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfInaccessibleOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub B1..ctor(x As System.Int32)", "Sub B1..ctor(x As System.String)" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("MyBase", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim baseType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B1") Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim result = LookupResult.GetInstance() binder.LookupMember(result, baseType, "Finalize", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Sub System.Object.Finalize()", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.LookupMember(result, baseType, "MemberwiseClone", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function System.Object.MemberwiseClone() As System.Object", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub #End Region #Region "Regression" <WorkItem(539107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539107")> <Fact()> Public Sub LookupAtLocationEndSubNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 End Sub 'BIND:"End Sub" End Class </file> </compilation>) Dim expected_in_lookupNames = { "count", "param1" } Dim expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539114")> <Fact()> Public Sub LookupAtLocationSubBlockNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) 'BIND:"Public Sub Method1(ByVal param1 As Integer)" Dim count As Integer = 45 End Sub End Class </file> </compilation>) Dim not_expected_in_lookupNames = { "count", "param1" } Dim not_expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539119")> <Fact()> Public Sub LookupSymbolsByNameIncorrectArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 'BIND:"45" End Sub End Class </file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="count", arity:=1) Assert.Empty(actual_lookupSymbols) End Sub <WorkItem(539130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539130")> <Fact()> Public Sub LookupWithNameZeroArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Method1(Of T)(i As T) End Sub Sub Method1(Of T, U)(i As T, j As U) End Sub Sub Method1(i As Integer) End Sub Sub Method1(i As Integer, j As Integer) End Sub Public Sub Main() Dim x As Integer = 45 'BIND:"45" End Sub End Module </file> </compilation>) Dim expected_in_lookupSymbols = { "Sub Module1.Method1(i As System.Int32)", "Sub Module1.Method1(i As System.Int32, j As System.Int32)" } Dim not_expected_in_lookupSymbols = { "Sub Module1.Method1(Of T)(i As T)", "Sub Module1.Method1(Of T, U)(i As T, j As U)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Method1", arity:=0) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(5004, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LookupExcludeInAppropriateNS() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 End Module </file> </compilation>, {SystemDataRef}) Dim not_expected_in_lookup = { "<CrtImplementationDetails>", "<CppImplementationDetails>" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Const position = 0 Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim actual_lookupSymbols = model.LookupSymbols(position) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookup(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookup(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunctionIgnoreReturnVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" Return 10 End Function End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("Dim", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim result = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing binder.Lookup(result, "Func1", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function Test.Func1() As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.Lookup(result, "x", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("x As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" 'BIND:"10" Return 10 End Function End Class </file> </compilation>) Dim expected_in_lookupNames = { "Func1", "x" } Dim expected_in_lookupSymbols = { "Func1 As System.Int32", "x As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527759")> <Fact()> Public Sub LookupAtLocationClassTypeBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527760")> <Fact()> Public Sub LookupAtLocationClassTypeStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527761")> <Fact()> Public Sub LookupAtLocationEndClassStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class 'BIND:"End Class" </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(539175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539175")> <Fact()> Public Sub LookupAtLocationNamespaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 'BIND:"Namespace NS1" Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS3" } Dim not_expected_in_lookupNames = { "NS2", "T1", "T2", "T3" } Dim expected_in_lookupSymbols = { "NS1", "NS3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2", "NS1.NS2.T1", "NS1.T2", "NS1.T3" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539177")> <Fact()> Public Sub LookupAtLocationEndNamespaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace 'BIND:"End Namespace" Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS2", "NS3", "T2", "T3" } Dim not_expected_in_lookupNames = { "T1" } Dim expected_in_lookupSymbols = { "NS1", "NS3", "NS1.NS2", "NS1.T2", "NS1.T3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2.T1" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) For Each expectedName In expected_in_lookupNames Assert.Contains(expectedName, actual_lookupNames) Next For Each notExpectedName In not_expected_in_lookupNames Assert.DoesNotContain(notExpectedName, actual_lookupNames) Next For Each expectedName In expected_in_lookupSymbols Assert.Contains(expectedName, actual_lookupSymbols_as_string) Next For Each notExpectedName In not_expected_in_lookupSymbols Assert.DoesNotContain(notExpectedName, actual_lookupSymbols_as_string) Next End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact()> Public Sub LookupAtLocationInterfaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationEndInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub sub1(ByVal i As Integer) End Interface 'BIND:"End Interface" </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527774")> <Fact()> Public Sub LookupAtLocationCompilationUnitSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Imports A1 = System 'BIND:"Imports A1 = System" </file> </compilation>) Dim expected_in_lookupNames = { "System", "Microsoft" } Dim expected_in_lookupSymbols = { "System", "Microsoft" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Equal(2, actual_lookupNames.Count) Assert.Equal(2, actual_lookupSymbols_as_string.Count) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527779")> <Fact()> Public Sub LookupAtLocationInheritsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Public Class C1 Public Sub C1Sub1() End Sub End Class Public Class C2 Inherits C1 'BIND:"Inherits C1" Public Sub C2Sub1() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "C1", "C2", "C2Sub1" } Dim not_expected_in_lookupNames = { "C1Sub1" } Dim expected_in_lookupSymbols = { "C1", "C2", "Sub C2.C2Sub1()" } Dim not_expected_in_lookupSymbols = { "Sub C1.C1Sub1()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(527780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527780")> <Fact()> Public Sub LookupAtLocationImplementsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub Sub1() End Interface Public Class ImplementationClass1 Implements Interface1 'BIND:"Implements Interface1" Sub Sub1() Implements Interface1.Sub1 End Sub Sub Sub2() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "ImplementationClass1", "Sub1", "Sub2" } Dim expected_in_lookupSymbols = { "Interface1", "ImplementationClass1", "Sub ImplementationClass1.Sub1()", "Sub ImplementationClass1.Sub2()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539232")> <Fact()> Public Sub LookupAtLocationInsideIfPartOfSingleLineIfStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me1 As Integer = 10" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me1" } Dim not_expected_in_lookupNames = { "me2" } Dim expected_in_lookupSymbols = { "me1 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me2 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(539234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539234")> <Fact()> Public Sub LookupAtLocationInsideElsePartOfSingleLineElseStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me2 As Integer = 20" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me2" } Dim not_expected_in_lookupNames = { "me1" } Dim expected_in_lookupSymbols = { "me2 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(542856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542856")> <Fact()> Public Sub LookupParamSingleLineLambdaExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub Bug10272_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Function End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub LookupSymbolsAtEOF() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim eof = tree.GetCompilationUnitRoot().FullSpan.End Assert.NotEqual(eof, 0) Dim symbols = model.LookupSymbols(eof) CompilationUtils.CheckSymbols(symbols, "Microsoft", "C", "System") End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 If True Then Dim y = 1 x=y 'BIND:"y" End If End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 Select Case 1 Case 1 Dim y = 1 x=y 'BIND:"y" End Select End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Test/Completion/TestVisualBasicSnippetInfoService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion <ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.VisualBasic, ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class TestVisualBasicSnippetInfoService Inherits VisualBasicSnippetInfoService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, Nothing, listenerProvider) End Sub Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String()) SyncLock cacheGuard snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray() snippetShortcuts = GetShortcutsHashFromSnippets(snippets) End SyncLock End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion <ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.VisualBasic, ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class TestVisualBasicSnippetInfoService Inherits VisualBasicSnippetInfoService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, Nothing, listenerProvider) End Sub Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String()) SyncLock cacheGuard snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray() snippetShortcuts = GetShortcutsHashFromSnippets(snippets) End SyncLock End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' but appears to have an // extension method by that name. Extension methods cannot be dynamically dispatched. Consider // casting the dynamic arguments or calling the extension method without the extension method // syntax. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { // Just assume we're not in an expression tree for the purposes of error recovery. var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, hasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' but appears to have an // extension method by that name. Extension methods cannot be dynamically dispatched. Consider // casting the dynamic arguments or calling the extension method without the extension method // syntax. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { // Just assume we're not in an expression tree for the purposes of error recovery. var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, hasErrors); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/HeaderMenuItemViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// The view model used for the header of TargetMenuItemViewModel. /// e.g. /// 'I↓ Implementing members' /// Method 'Bar' /// </summary> internal class HeaderMenuItemViewModel : InheritanceMenuItemViewModel { public HeaderMenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) : base(displayContent, imageMoniker, automationName) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// The view model used for the header of TargetMenuItemViewModel. /// e.g. /// 'I↓ Implementing members' /// Method 'Bar' /// </summary> internal class HeaderMenuItemViewModel : InheritanceMenuItemViewModel { public HeaderMenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) : base(displayContent, imageMoniker, automationName) { } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetingCustomAttributes.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.[Text] Imports System.Collections.Generic Imports System.Linq Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting #If Not Retargeting Then Public Class RetargetCustomAttributes Inherits BasicTestBase Public Sub New() MyBase.New() End Sub Friend Class Test01 Public c1 As VisualBasicCompilationReference Public c2 As VisualBasicCompilationReference Public c1MscorLibAssemblyRef As AssemblySymbol Public c2MscorlibAssemblyRef As AssemblySymbol Public OldMsCorLib_debuggerTypeProxyAttributeType As NamedTypeSymbol Public NewMsCorLib_debuggerTypeProxyAttributeType As NamedTypeSymbol Public OldMsCorLib_debuggerTypeProxyAttributeCtor As MethodSymbol Public NewMsCorLib_debuggerTypeProxyAttributeCtor As MethodSymbol Public OldMsCorLib_systemType As NamedTypeSymbol Public NewMsCorLib_systemType As NamedTypeSymbol Private Shared ReadOnly s_attribute As AttributeDescription = New AttributeDescription( "System.Diagnostics", "DebuggerTypeProxyAttribute", {New Byte() {CByte(SignatureAttributes.Instance), 1, CByte(SignatureTypeCode.Void), CByte(SignatureTypeCode.TypeHandle), CByte(AttributeDescription.TypeHandleTarget.SystemType)}}) Public Sub New() Dim source = <compilation name="C1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Assembly: DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> <Module: DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Class TestClass <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public testField As Integer <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public ReadOnly Property TestProperty() As <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Integer Get Return testField End Get End Property <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public Function TestMethod(Of T)(<DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> ByVal testParameter As T) As <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> T Return testParameter End Function End Class]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source, {OldMsCorLib}) c1 = New VisualBasicCompilationReference(compilation1) Dim c1Assembly = compilation1.Assembly Dim compilation2 = VisualBasicCompilation.Create("C2", references:={NewMsCorLib, c1}) c2 = New VisualBasicCompilationReference(compilation2) Dim c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1) Assert.NotSame(c1Assembly, c1AsmRef) c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib) c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib) Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef) OldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type") NewMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type") Assert.NotSame(OldMsCorLib_systemType, NewMsCorLib_systemType) OldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute") NewMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute") Assert.NotSame(OldMsCorLib_debuggerTypeProxyAttributeType, NewMsCorLib_debuggerTypeProxyAttributeType) OldMsCorLib_debuggerTypeProxyAttributeCtor = DirectCast(OldMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor"). Where(Function(m) DirectCast(m, MethodSymbol).ParameterCount = 1 AndAlso TypeSymbol.Equals(DirectCast(m, MethodSymbol).Parameters(0).Type, OldMsCorLib_systemType, TypeCompareKind.ConsiderEverything)).[Single](), MethodSymbol) NewMsCorLib_debuggerTypeProxyAttributeCtor = DirectCast(NewMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor"). Where(Function(m) DirectCast(m, MethodSymbol).ParameterCount = 1 AndAlso TypeSymbol.Equals(DirectCast(m, MethodSymbol).Parameters(0).Type, NewMsCorLib_systemType, TypeCompareKind.ConsiderEverything)).[Single](), MethodSymbol) Assert.NotSame(OldMsCorLib_debuggerTypeProxyAttributeCtor, NewMsCorLib_debuggerTypeProxyAttributeCtor) End Sub Public Sub TestAttributeRetargeting(symbol As Symbol) ' Verify GetAttributes() TestAttributeRetargeting(symbol.GetAttributes()) ' Verify GetAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(NewMsCorLib_debuggerTypeProxyAttributeType)) ' GetAttributes(AttributeType from Underlying assembly) should find nothing. Assert.Empty(symbol.GetAttributes(OldMsCorLib_debuggerTypeProxyAttributeType)) ' Verify GetAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(NewMsCorLib_debuggerTypeProxyAttributeCtor)) ' Verify GetAttributes(AttributeCtor from Underlying assembly) Assert.Empty(symbol.GetAttributes(OldMsCorLib_debuggerTypeProxyAttributeCtor)) ' Verify GetAttributes(namespaceName, typeName, ctorSignature) TestAttributeRetargeting(symbol.GetAttributes(s_attribute).AsEnumerable()) End Sub Public Sub TestAttributeRetargeting_ReturnTypeAttributes(symbol As MethodSymbol) ' Verify ReturnTypeAttributes TestAttributeRetargeting(symbol.GetReturnTypeAttributes()) End Sub Private Sub TestAttributeRetargeting(attributes As IEnumerable(Of VisualBasicAttributeData)) Assert.Equal(1, attributes.Count) Dim attribute = attributes.First() Assert.IsType(Of RetargetingAttributeData)(attribute) Assert.Same(NewMsCorLib_debuggerTypeProxyAttributeType, attribute.AttributeClass) Assert.Same(NewMsCorLib_debuggerTypeProxyAttributeCtor, attribute.AttributeConstructor) Assert.Same(NewMsCorLib_systemType, attribute.AttributeConstructor.Parameters(0).Type) Assert.Equal(1, attribute.CommonConstructorArguments.Length) attribute.VerifyValue(0, TypedConstantKind.Type, NewMsCorLib_systemType) Assert.Equal(2, attribute.CommonNamedArguments.Length) attribute.VerifyValue(0, "Target", TypedConstantKind.Type, GetType(Integer())) attribute.VerifyValue(1, "TargetTypeName", TypedConstantKind.Primitive, "IntArrayType") End Sub End Class Private Shared ReadOnly Property OldMsCorLib As MetadataReference Get Return TestMetadata.Net40.mscorlib End Get End Property Private Shared ReadOnly Property NewMsCorLib As MetadataReference Get Return TestMetadata.Net451.mscorlib End Get End Property <Fact> Public Sub Test01_AssemblyAttribute() Dim test As New Test01() Dim c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1) Assert.IsType(Of RetargetingAssemblySymbol)(c1AsmRef) test.TestAttributeRetargeting(c1AsmRef) End Sub <Fact> Public Sub Test01_ModuleAttribute() Dim test As New Test01() Dim c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1) Dim c1ModuleSym = c1AsmRef.Modules(0) Assert.IsType(Of RetargetingModuleSymbol)(c1ModuleSym) test.TestAttributeRetargeting(c1ModuleSym) End Sub <Fact> Public Sub Test01_NamedTypeAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Assert.IsType(Of RetargetingNamedTypeSymbol)(testClass) test.TestAttributeRetargeting(testClass) End Sub <Fact> Public Sub Test01_FieldAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testField As FieldSymbol = testClass.GetMembers("testField").OfType(Of FieldSymbol)().[Single]() Assert.IsType(Of RetargetingFieldSymbol)(testField) test.TestAttributeRetargeting(testField) End Sub <Fact> Public Sub Test01_PropertyAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testProperty As PropertySymbol = testClass.GetMembers("TestProperty").OfType(Of PropertySymbol)().[Single]() Assert.IsType(Of RetargetingPropertySymbol)(testProperty) test.TestAttributeRetargeting(testProperty) Dim testMethod As MethodSymbol = testProperty.GetMethod Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod) End Sub <Fact> Public Sub Test01_MethodAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting(testMethod) End Sub <Fact> Public Sub Test01_ParameterAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) Dim testParameter As ParameterSymbol = testMethod.Parameters(0) Assert.True((TryCast(testParameter, RetargetingParameterSymbol)) IsNot Nothing, "RetargetingMethodSymbol's parameter must be a RetargetingParameterSymbol") test.TestAttributeRetargeting(testParameter) End Sub <Fact> Public Sub Test01_ReturnTypeAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod) End Sub <Fact> <WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")> Public Sub NullArrays() Dim source1 = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(a As Object(), b As Integer()) End Sub Public Property P As Object() Public F As Integer() End Class <A(Nothing, Nothing, P:=Nothing, F:=Nothing)> Class C End Class ]]></file> </compilation> Dim source2 = <compilation><file></file></compilation> Dim c1 = CreateEmptyCompilationWithReferences(source1, {OldMsCorLib}) Dim c2 = CreateEmptyCompilationWithReferences(source2, {NewMsCorLib, New VisualBasicCompilationReference(c1)}) Dim c = c2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.IsType(Of RetargetingNamedTypeSymbol)(c) Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.True(args(0).IsNull) Assert.Equal("Object()", args(0).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(0).Value) Assert.True(args(1).IsNull) Assert.Equal("Integer()", args(1).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(1).Value) Dim named = attr.NamedArguments.ToDictionary(Function(e) e.Key, Function(e) e.Value) Assert.True(named("P").IsNull) Assert.Equal("Object()", named("P").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("P").Value) Assert.True(named("F").IsNull) Assert.Equal("Integer()", named("F").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("F").Value) End Sub End Class #End If End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.[Text] Imports System.Collections.Generic Imports System.Linq Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting #If Not Retargeting Then Public Class RetargetCustomAttributes Inherits BasicTestBase Public Sub New() MyBase.New() End Sub Friend Class Test01 Public c1 As VisualBasicCompilationReference Public c2 As VisualBasicCompilationReference Public c1MscorLibAssemblyRef As AssemblySymbol Public c2MscorlibAssemblyRef As AssemblySymbol Public OldMsCorLib_debuggerTypeProxyAttributeType As NamedTypeSymbol Public NewMsCorLib_debuggerTypeProxyAttributeType As NamedTypeSymbol Public OldMsCorLib_debuggerTypeProxyAttributeCtor As MethodSymbol Public NewMsCorLib_debuggerTypeProxyAttributeCtor As MethodSymbol Public OldMsCorLib_systemType As NamedTypeSymbol Public NewMsCorLib_systemType As NamedTypeSymbol Private Shared ReadOnly s_attribute As AttributeDescription = New AttributeDescription( "System.Diagnostics", "DebuggerTypeProxyAttribute", {New Byte() {CByte(SignatureAttributes.Instance), 1, CByte(SignatureTypeCode.Void), CByte(SignatureTypeCode.TypeHandle), CByte(AttributeDescription.TypeHandleTarget.SystemType)}}) Public Sub New() Dim source = <compilation name="C1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Assembly: DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> <Module: DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Class TestClass <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public testField As Integer <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public ReadOnly Property TestProperty() As <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Integer Get Return testField End Get End Property <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> Public Function TestMethod(Of T)(<DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> ByVal testParameter As T) As <DebuggerTypeProxyAttribute(GetType(System.Type), Target := GetType(Integer()), TargetTypeName := "IntArrayType")> T Return testParameter End Function End Class]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source, {OldMsCorLib}) c1 = New VisualBasicCompilationReference(compilation1) Dim c1Assembly = compilation1.Assembly Dim compilation2 = VisualBasicCompilation.Create("C2", references:={NewMsCorLib, c1}) c2 = New VisualBasicCompilationReference(compilation2) Dim c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1) Assert.NotSame(c1Assembly, c1AsmRef) c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib) c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib) Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef) OldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type") NewMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type") Assert.NotSame(OldMsCorLib_systemType, NewMsCorLib_systemType) OldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute") NewMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute") Assert.NotSame(OldMsCorLib_debuggerTypeProxyAttributeType, NewMsCorLib_debuggerTypeProxyAttributeType) OldMsCorLib_debuggerTypeProxyAttributeCtor = DirectCast(OldMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor"). Where(Function(m) DirectCast(m, MethodSymbol).ParameterCount = 1 AndAlso TypeSymbol.Equals(DirectCast(m, MethodSymbol).Parameters(0).Type, OldMsCorLib_systemType, TypeCompareKind.ConsiderEverything)).[Single](), MethodSymbol) NewMsCorLib_debuggerTypeProxyAttributeCtor = DirectCast(NewMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor"). Where(Function(m) DirectCast(m, MethodSymbol).ParameterCount = 1 AndAlso TypeSymbol.Equals(DirectCast(m, MethodSymbol).Parameters(0).Type, NewMsCorLib_systemType, TypeCompareKind.ConsiderEverything)).[Single](), MethodSymbol) Assert.NotSame(OldMsCorLib_debuggerTypeProxyAttributeCtor, NewMsCorLib_debuggerTypeProxyAttributeCtor) End Sub Public Sub TestAttributeRetargeting(symbol As Symbol) ' Verify GetAttributes() TestAttributeRetargeting(symbol.GetAttributes()) ' Verify GetAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(NewMsCorLib_debuggerTypeProxyAttributeType)) ' GetAttributes(AttributeType from Underlying assembly) should find nothing. Assert.Empty(symbol.GetAttributes(OldMsCorLib_debuggerTypeProxyAttributeType)) ' Verify GetAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(NewMsCorLib_debuggerTypeProxyAttributeCtor)) ' Verify GetAttributes(AttributeCtor from Underlying assembly) Assert.Empty(symbol.GetAttributes(OldMsCorLib_debuggerTypeProxyAttributeCtor)) ' Verify GetAttributes(namespaceName, typeName, ctorSignature) TestAttributeRetargeting(symbol.GetAttributes(s_attribute).AsEnumerable()) End Sub Public Sub TestAttributeRetargeting_ReturnTypeAttributes(symbol As MethodSymbol) ' Verify ReturnTypeAttributes TestAttributeRetargeting(symbol.GetReturnTypeAttributes()) End Sub Private Sub TestAttributeRetargeting(attributes As IEnumerable(Of VisualBasicAttributeData)) Assert.Equal(1, attributes.Count) Dim attribute = attributes.First() Assert.IsType(Of RetargetingAttributeData)(attribute) Assert.Same(NewMsCorLib_debuggerTypeProxyAttributeType, attribute.AttributeClass) Assert.Same(NewMsCorLib_debuggerTypeProxyAttributeCtor, attribute.AttributeConstructor) Assert.Same(NewMsCorLib_systemType, attribute.AttributeConstructor.Parameters(0).Type) Assert.Equal(1, attribute.CommonConstructorArguments.Length) attribute.VerifyValue(0, TypedConstantKind.Type, NewMsCorLib_systemType) Assert.Equal(2, attribute.CommonNamedArguments.Length) attribute.VerifyValue(0, "Target", TypedConstantKind.Type, GetType(Integer())) attribute.VerifyValue(1, "TargetTypeName", TypedConstantKind.Primitive, "IntArrayType") End Sub End Class Private Shared ReadOnly Property OldMsCorLib As MetadataReference Get Return TestMetadata.Net40.mscorlib End Get End Property Private Shared ReadOnly Property NewMsCorLib As MetadataReference Get Return TestMetadata.Net451.mscorlib End Get End Property <Fact> Public Sub Test01_AssemblyAttribute() Dim test As New Test01() Dim c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1) Assert.IsType(Of RetargetingAssemblySymbol)(c1AsmRef) test.TestAttributeRetargeting(c1AsmRef) End Sub <Fact> Public Sub Test01_ModuleAttribute() Dim test As New Test01() Dim c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1) Dim c1ModuleSym = c1AsmRef.Modules(0) Assert.IsType(Of RetargetingModuleSymbol)(c1ModuleSym) test.TestAttributeRetargeting(c1ModuleSym) End Sub <Fact> Public Sub Test01_NamedTypeAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Assert.IsType(Of RetargetingNamedTypeSymbol)(testClass) test.TestAttributeRetargeting(testClass) End Sub <Fact> Public Sub Test01_FieldAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testField As FieldSymbol = testClass.GetMembers("testField").OfType(Of FieldSymbol)().[Single]() Assert.IsType(Of RetargetingFieldSymbol)(testField) test.TestAttributeRetargeting(testField) End Sub <Fact> Public Sub Test01_PropertyAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testProperty As PropertySymbol = testClass.GetMembers("TestProperty").OfType(Of PropertySymbol)().[Single]() Assert.IsType(Of RetargetingPropertySymbol)(testProperty) test.TestAttributeRetargeting(testProperty) Dim testMethod As MethodSymbol = testProperty.GetMethod Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod) End Sub <Fact> Public Sub Test01_MethodAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting(testMethod) End Sub <Fact> Public Sub Test01_ParameterAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) Dim testParameter As ParameterSymbol = testMethod.Parameters(0) Assert.True((TryCast(testParameter, RetargetingParameterSymbol)) IsNot Nothing, "RetargetingMethodSymbol's parameter must be a RetargetingParameterSymbol") test.TestAttributeRetargeting(testParameter) End Sub <Fact> Public Sub Test01_ReturnTypeAttribute() Dim test As New Test01() Dim testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").[Single]() Dim testMethod As MethodSymbol = testClass.GetMembers("TestMethod").OfType(Of MethodSymbol)().[Single]() Assert.IsType(Of RetargetingMethodSymbol)(testMethod) test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod) End Sub <Fact> <WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")> Public Sub NullArrays() Dim source1 = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(a As Object(), b As Integer()) End Sub Public Property P As Object() Public F As Integer() End Class <A(Nothing, Nothing, P:=Nothing, F:=Nothing)> Class C End Class ]]></file> </compilation> Dim source2 = <compilation><file></file></compilation> Dim c1 = CreateEmptyCompilationWithReferences(source1, {OldMsCorLib}) Dim c2 = CreateEmptyCompilationWithReferences(source2, {NewMsCorLib, New VisualBasicCompilationReference(c1)}) Dim c = c2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.IsType(Of RetargetingNamedTypeSymbol)(c) Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.True(args(0).IsNull) Assert.Equal("Object()", args(0).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(0).Value) Assert.True(args(1).IsNull) Assert.Equal("Integer()", args(1).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(1).Value) Dim named = attr.NamedArguments.ToDictionary(Function(e) e.Key, Function(e) e.Value) Assert.True(named("P").IsNull) Assert.Equal("Object()", named("P").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("P").Value) Assert.True(named("F").IsNull) Assert.Equal("Integer()", named("F").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("F").Value) End Sub End Class #End If End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_Razor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: 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.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: true); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Impl/CodeModel/Interop/IMethodXML2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("58A26C00-BE6F-4B32-803A-98F5B7806C76")] internal interface IMethodXML2 { /// <summary> /// Returns a string reader of the XML. Unlike IMethodXML, this doesn't require us to convert our XML string to /// BSTR and back. /// </summary> /// <returns>A System.IO.StringReader, even though we just say object here.</returns> [return: MarshalAs(UnmanagedType.IUnknown)] object GetXML(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("58A26C00-BE6F-4B32-803A-98F5B7806C76")] internal interface IMethodXML2 { /// <summary> /// Returns a string reader of the XML. Unlike IMethodXML, this doesn't require us to convert our XML string to /// BSTR and back. /// </summary> /// <returns>A System.IO.StringReader, even though we just say object here.</returns> [return: MarshalAs(UnmanagedType.IUnknown)] object GetXML(); } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/InternalDiagnosticsPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Guid(Guids.RoslynOptionPageInternalDiagnosticsIdString)] internal class InternalDiagnosticsPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { return new InternalOptionsControl(nameof(InternalDiagnosticsOptions), optionStore); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Guid(Guids.RoslynOptionPageInternalDiagnosticsIdString)] internal class InternalDiagnosticsPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { return new InternalOptionsControl(nameof(InternalDiagnosticsOptions), optionStore); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpOrganizing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpOrganizing : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpOrganizing(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpOrganizing)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)] public void RemoveAndSort() { SetUpEditor(@"$$ using C; using B; using A; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); VisualStudio.ExecuteCommand("Edit.RemoveAndSort"); VisualStudio.Editor.Verify.TextContains(@" using A; using C; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpOrganizing : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpOrganizing(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpOrganizing)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)] public void RemoveAndSort() { SetUpEditor(@"$$ using C; using B; using A; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); VisualStudio.ExecuteCommand("Edit.RemoveAndSort"); VisualStudio.Editor.Verify.TextContains(@" using A; using C; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationMethodInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationMethodInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo> s_methodToInfoMap = new(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly bool _isPartial; private readonly bool _isAsync; private readonly ImmutableArray<SyntaxNode> _statements; private readonly ImmutableArray<SyntaxNode> _handlesExpressions; private CodeGenerationMethodInfo( bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { _isNew = isNew; _isUnsafe = isUnsafe; _isPartial = isPartial; _isAsync = isAsync; _statements = statements.NullToEmpty(); _handlesExpressions = handlesExpressions.NullToEmpty(); } public static void Attach( IMethodSymbol method, bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { var info = new CodeGenerationMethodInfo(isNew, isUnsafe, isPartial, isAsync, statements, handlesExpressions); s_methodToInfoMap.Add(method, info); } private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method) { s_methodToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol method) => GetStatements(GetInfo(method)); public static ImmutableArray<SyntaxNode> GetHandlesExpressions(IMethodSymbol method) => GetHandlesExpressions(GetInfo(method)); public static bool GetIsNew(IMethodSymbol method) => GetIsNew(GetInfo(method)); public static bool GetIsUnsafe(IMethodSymbol method) => GetIsUnsafe(GetInfo(method)); public static bool GetIsPartial(IMethodSymbol method) => GetIsPartial(GetInfo(method)); public static bool GetIsAsyncMethod(IMethodSymbol method) => GetIsAsyncMethod(GetInfo(method)); private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationMethodInfo info) => info?._statements ?? ImmutableArray<SyntaxNode>.Empty; private static ImmutableArray<SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info) => info?._handlesExpressions ?? ImmutableArray<SyntaxNode>.Empty; private static bool GetIsNew(CodeGenerationMethodInfo info) => info != null && info._isNew; private static bool GetIsUnsafe(CodeGenerationMethodInfo info) => info != null && info._isUnsafe; private static bool GetIsPartial(CodeGenerationMethodInfo info) => info != null && info._isPartial; private static bool GetIsAsyncMethod(CodeGenerationMethodInfo info) => info != null && info._isAsync; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationMethodInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo> s_methodToInfoMap = new(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly bool _isPartial; private readonly bool _isAsync; private readonly ImmutableArray<SyntaxNode> _statements; private readonly ImmutableArray<SyntaxNode> _handlesExpressions; private CodeGenerationMethodInfo( bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { _isNew = isNew; _isUnsafe = isUnsafe; _isPartial = isPartial; _isAsync = isAsync; _statements = statements.NullToEmpty(); _handlesExpressions = handlesExpressions.NullToEmpty(); } public static void Attach( IMethodSymbol method, bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { var info = new CodeGenerationMethodInfo(isNew, isUnsafe, isPartial, isAsync, statements, handlesExpressions); s_methodToInfoMap.Add(method, info); } private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method) { s_methodToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol method) => GetStatements(GetInfo(method)); public static ImmutableArray<SyntaxNode> GetHandlesExpressions(IMethodSymbol method) => GetHandlesExpressions(GetInfo(method)); public static bool GetIsNew(IMethodSymbol method) => GetIsNew(GetInfo(method)); public static bool GetIsUnsafe(IMethodSymbol method) => GetIsUnsafe(GetInfo(method)); public static bool GetIsPartial(IMethodSymbol method) => GetIsPartial(GetInfo(method)); public static bool GetIsAsyncMethod(IMethodSymbol method) => GetIsAsyncMethod(GetInfo(method)); private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationMethodInfo info) => info?._statements ?? ImmutableArray<SyntaxNode>.Empty; private static ImmutableArray<SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info) => info?._handlesExpressions ?? ImmutableArray<SyntaxNode>.Empty; private static bool GetIsNew(CodeGenerationMethodInfo info) => info != null && info._isNew; private static bool GetIsUnsafe(CodeGenerationMethodInfo info) => info != null && info._isUnsafe; private static bool GetIsPartial(CodeGenerationMethodInfo info) => info != null && info._isPartial; private static bool GetIsAsyncMethod(CodeGenerationMethodInfo info) => info != null && info._isAsync; } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/Core/Portable/Shared/Utilities/XmlFragmentParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Xml; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// An XML parser that is designed to parse small fragments of XML such as those that appear in documentation comments. /// PERF: We try to re-use the same underlying <see cref="XmlReader"/> to reduce the allocation costs of multiple parses. /// </summary> internal sealed class XmlFragmentParser { private XmlReader _xmlReader; private readonly Reader _textReader = new(); private static readonly ObjectPool<XmlFragmentParser> s_pool = SharedPools.Default<XmlFragmentParser>(); /// <summary> /// Parse the given XML fragment. The given callback is executed until either the end of the fragment /// is reached or an exception occurs. /// </summary> /// <typeparam name="TArg">Type of an additional argument passed to the <paramref name="callback"/> delegate.</typeparam> /// <param name="xmlFragment">The fragment to parse.</param> /// <param name="callback">Action to execute while there is still more to read.</param> /// <param name="arg">Additional argument passed to the callback.</param> /// <remarks> /// It is important that the <paramref name="callback"/> action advances the <see cref="XmlReader"/>, /// otherwise parsing will never complete. /// </remarks> public static void ParseFragment<TArg>(string xmlFragment, Action<XmlReader, TArg> callback, TArg arg) { var instance = s_pool.Allocate(); try { instance.ParseInternal(xmlFragment, callback, arg); } finally { s_pool.Free(instance); } } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private void ParseInternal<TArg>(string text, Action<XmlReader, TArg> callback, TArg arg) { _textReader.SetText(text); if (_xmlReader == null) { _xmlReader = XmlReader.Create(_textReader, s_xmlSettings); } try { while (!ReachedEnd) { if (BeforeStart) { // Skip over the synthetic root element and first node _xmlReader.Read(); } else { callback(_xmlReader, arg); } } // Read the final EndElement to reset things for the next user. _xmlReader.ReadEndElement(); } catch { // The reader is in a bad state, so dispose of it and recreate a new one next time we get called. _xmlReader.Dispose(); _xmlReader = null; _textReader.Reset(); throw; } } private bool BeforeStart { get { // Depth 0 = Document root // Depth 1 = Synthetic wrapper, "CurrentElement" // Depth 2 = Start of user's fragment. return _xmlReader.Depth < 2; } } private bool ReachedEnd { get { return _xmlReader.Depth == 1 && _xmlReader.NodeType == XmlNodeType.EndElement && _xmlReader.LocalName == Reader.CurrentElementName; } } /// <summary> /// A text reader over a synthesized XML stream consisting of a single root element followed by a potentially /// infinite stream of fragments. Each time "SetText" is called the stream is rewound to the element immediately /// following the synthetic root node. /// </summary> private sealed class Reader : TextReader { /// <summary> /// Current text to validate. /// </summary> private string _text; private int _position; // Base the root element name on a GUID to avoid accidental (or intentional) collisions. An underscore is // prefixed because element names must not start with a number. private static readonly string s_rootElementName = "_" + Guid.NewGuid().ToString("N"); // We insert an extra synthetic element name to allow for raw text at the root internal static readonly string CurrentElementName = "_" + Guid.NewGuid().ToString("N"); private static readonly string s_rootStart = "<" + s_rootElementName + ">"; private static readonly string s_currentStart = "<" + CurrentElementName + ">"; private static readonly string s_currentEnd = "</" + CurrentElementName + ">"; public void Reset() { _text = null; _position = 0; } public void SetText(string text) { _text = text; // The first read shall read the <root>, // the subsequents reads shall start with <current> element if (_position > 0) { _position = s_rootStart.Length; } } public override int Read(char[] buffer, int index, int count) { if (count == 0) { return 0; } // The stream synthesizes an XML document with: // 1. A root element start tag // 2. Current element start tag // 3. The user text (xml fragments) // 4. Current element end tag var initialCount = count; // <root> _position += EncodeAndAdvance(s_rootStart, _position, buffer, ref index, ref count); // <current> _position += EncodeAndAdvance(s_currentStart, _position - s_rootStart.Length, buffer, ref index, ref count); // text _position += EncodeAndAdvance(_text, _position - s_rootStart.Length - s_currentStart.Length, buffer, ref index, ref count); // </current> _position += EncodeAndAdvance(s_currentEnd, _position - s_rootStart.Length - s_currentStart.Length - _text.Length, buffer, ref index, ref count); // Pretend that the stream is infinite, i.e. never return 0 characters read. if (initialCount == count) { buffer[index++] = ' '; count--; } return initialCount - count; } private static int EncodeAndAdvance(string src, int srcIndex, char[] dest, ref int destIndex, ref int destCount) { if (destCount == 0 || srcIndex < 0 || srcIndex >= src.Length) { return 0; } var charCount = Math.Min(src.Length - srcIndex, destCount); Debug.Assert(charCount > 0); src.CopyTo(srcIndex, dest, destIndex, charCount); destIndex += charCount; destCount -= charCount; Debug.Assert(destCount >= 0); return charCount; } public override int Read() { // XmlReader does not call this API throw ExceptionUtilities.Unreachable; } public override int Peek() { // XmlReader does not call this API 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; using System.Diagnostics; using System.IO; using System.Xml; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// An XML parser that is designed to parse small fragments of XML such as those that appear in documentation comments. /// PERF: We try to re-use the same underlying <see cref="XmlReader"/> to reduce the allocation costs of multiple parses. /// </summary> internal sealed class XmlFragmentParser { private XmlReader _xmlReader; private readonly Reader _textReader = new(); private static readonly ObjectPool<XmlFragmentParser> s_pool = SharedPools.Default<XmlFragmentParser>(); /// <summary> /// Parse the given XML fragment. The given callback is executed until either the end of the fragment /// is reached or an exception occurs. /// </summary> /// <typeparam name="TArg">Type of an additional argument passed to the <paramref name="callback"/> delegate.</typeparam> /// <param name="xmlFragment">The fragment to parse.</param> /// <param name="callback">Action to execute while there is still more to read.</param> /// <param name="arg">Additional argument passed to the callback.</param> /// <remarks> /// It is important that the <paramref name="callback"/> action advances the <see cref="XmlReader"/>, /// otherwise parsing will never complete. /// </remarks> public static void ParseFragment<TArg>(string xmlFragment, Action<XmlReader, TArg> callback, TArg arg) { var instance = s_pool.Allocate(); try { instance.ParseInternal(xmlFragment, callback, arg); } finally { s_pool.Free(instance); } } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private void ParseInternal<TArg>(string text, Action<XmlReader, TArg> callback, TArg arg) { _textReader.SetText(text); if (_xmlReader == null) { _xmlReader = XmlReader.Create(_textReader, s_xmlSettings); } try { while (!ReachedEnd) { if (BeforeStart) { // Skip over the synthetic root element and first node _xmlReader.Read(); } else { callback(_xmlReader, arg); } } // Read the final EndElement to reset things for the next user. _xmlReader.ReadEndElement(); } catch { // The reader is in a bad state, so dispose of it and recreate a new one next time we get called. _xmlReader.Dispose(); _xmlReader = null; _textReader.Reset(); throw; } } private bool BeforeStart { get { // Depth 0 = Document root // Depth 1 = Synthetic wrapper, "CurrentElement" // Depth 2 = Start of user's fragment. return _xmlReader.Depth < 2; } } private bool ReachedEnd { get { return _xmlReader.Depth == 1 && _xmlReader.NodeType == XmlNodeType.EndElement && _xmlReader.LocalName == Reader.CurrentElementName; } } /// <summary> /// A text reader over a synthesized XML stream consisting of a single root element followed by a potentially /// infinite stream of fragments. Each time "SetText" is called the stream is rewound to the element immediately /// following the synthetic root node. /// </summary> private sealed class Reader : TextReader { /// <summary> /// Current text to validate. /// </summary> private string _text; private int _position; // Base the root element name on a GUID to avoid accidental (or intentional) collisions. An underscore is // prefixed because element names must not start with a number. private static readonly string s_rootElementName = "_" + Guid.NewGuid().ToString("N"); // We insert an extra synthetic element name to allow for raw text at the root internal static readonly string CurrentElementName = "_" + Guid.NewGuid().ToString("N"); private static readonly string s_rootStart = "<" + s_rootElementName + ">"; private static readonly string s_currentStart = "<" + CurrentElementName + ">"; private static readonly string s_currentEnd = "</" + CurrentElementName + ">"; public void Reset() { _text = null; _position = 0; } public void SetText(string text) { _text = text; // The first read shall read the <root>, // the subsequents reads shall start with <current> element if (_position > 0) { _position = s_rootStart.Length; } } public override int Read(char[] buffer, int index, int count) { if (count == 0) { return 0; } // The stream synthesizes an XML document with: // 1. A root element start tag // 2. Current element start tag // 3. The user text (xml fragments) // 4. Current element end tag var initialCount = count; // <root> _position += EncodeAndAdvance(s_rootStart, _position, buffer, ref index, ref count); // <current> _position += EncodeAndAdvance(s_currentStart, _position - s_rootStart.Length, buffer, ref index, ref count); // text _position += EncodeAndAdvance(_text, _position - s_rootStart.Length - s_currentStart.Length, buffer, ref index, ref count); // </current> _position += EncodeAndAdvance(s_currentEnd, _position - s_rootStart.Length - s_currentStart.Length - _text.Length, buffer, ref index, ref count); // Pretend that the stream is infinite, i.e. never return 0 characters read. if (initialCount == count) { buffer[index++] = ' '; count--; } return initialCount - count; } private static int EncodeAndAdvance(string src, int srcIndex, char[] dest, ref int destIndex, ref int destCount) { if (destCount == 0 || srcIndex < 0 || srcIndex >= src.Length) { return 0; } var charCount = Math.Min(src.Length - srcIndex, destCount); Debug.Assert(charCount > 0); src.CopyTo(srcIndex, dest, destIndex, charCount); destIndex += charCount; destCount -= charCount; Debug.Assert(destCount >= 0); return charCount; } public override int Read() { // XmlReader does not call this API throw ExceptionUtilities.Unreachable; } public override int Peek() { // XmlReader does not call this API throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService : IFindUsagesService, IFindUsagesLSPService { } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService : IFindUsagesService, IFindUsagesLSPService { } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Test/Symbol/Symbols/ErrorTypeSymbolTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ErrorTypeSymbolTests : CSharpTestBase { [WorkItem(546143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546143")] [Fact] public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateCompilation(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Binding types in source, no missing types. var source2 = @"class C1<T, U> : A<T>.B<U> { } class C2<T, U> : A<T>.B<U> { } class C3<T> : A<T>.B<object> { } class C4<T> : A<object>.B<T> { } class C5 : A<object>.B<int> { } class C6 : A<string>.B<object> { } class C7 : A<string>.B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = MetadataReference.CreateFromImage(compilation2.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateCompilation(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateCompilation(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateCompilation(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); } private void CompareConstructedErrorTypes(CSharpCompilation compilation, bool missingTypes, bool fromSource) { // Get all root types. var allTypes = compilation.GlobalNamespace.GetTypeMembers(); // Get base class for each type named "C?". var types = new[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7" }.Select(name => allTypes.First(t => t.Name == name).BaseType()).ToArray(); foreach (var type in types) { var constructedFrom = type.ConstructedFrom; Assert.NotEqual(type, constructedFrom); if (missingTypes) { Assert.True(type.IsErrorType()); Assert.True(constructedFrom.IsErrorType()); var extendedError = constructedFrom as ExtendedErrorTypeSymbol; if (fromSource) { Assert.NotNull(extendedError); } else { Assert.Null(extendedError); } } else { Assert.False(type.IsErrorType()); Assert.False(constructedFrom.IsErrorType()); } } // Compare pairs of types. The only error types that // should compare equal are C6 and C7. const int n = 7; for (int i = 0; i < n - 1; i++) { var typeA = types[i]; for (int j = i + 1; j < n; j++) { var typeB = types[j]; bool expectedEqual = (i == 5) && (j == 6); Assert.Equal(TypeSymbol.Equals(typeA, typeB, TypeCompareKind.ConsiderEverything2), expectedEqual); } } } [WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")] [Fact] public void ErrorInfo_01() { var error = new MissingMetadataTypeSymbol.Nested(new UnsupportedMetadataTypeSymbol(), "Test", 0, false); var info = error.ErrorInfo; Assert.Equal(ErrorCode.ERR_BogusType, (ErrorCode)info.Code); Assert.Null(error.ContainingModule); Assert.Null(error.ContainingAssembly); Assert.NotNull(error.ContainingSymbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ErrorTypeSymbolTests : CSharpTestBase { [WorkItem(546143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546143")] [Fact] public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateCompilation(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Binding types in source, no missing types. var source2 = @"class C1<T, U> : A<T>.B<U> { } class C2<T, U> : A<T>.B<U> { } class C3<T> : A<T>.B<object> { } class C4<T> : A<object>.B<T> { } class C5 : A<object>.B<int> { } class C6 : A<string>.B<object> { } class C7 : A<string>.B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = MetadataReference.CreateFromImage(compilation2.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateCompilation(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateCompilation(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateCompilation(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); } private void CompareConstructedErrorTypes(CSharpCompilation compilation, bool missingTypes, bool fromSource) { // Get all root types. var allTypes = compilation.GlobalNamespace.GetTypeMembers(); // Get base class for each type named "C?". var types = new[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7" }.Select(name => allTypes.First(t => t.Name == name).BaseType()).ToArray(); foreach (var type in types) { var constructedFrom = type.ConstructedFrom; Assert.NotEqual(type, constructedFrom); if (missingTypes) { Assert.True(type.IsErrorType()); Assert.True(constructedFrom.IsErrorType()); var extendedError = constructedFrom as ExtendedErrorTypeSymbol; if (fromSource) { Assert.NotNull(extendedError); } else { Assert.Null(extendedError); } } else { Assert.False(type.IsErrorType()); Assert.False(constructedFrom.IsErrorType()); } } // Compare pairs of types. The only error types that // should compare equal are C6 and C7. const int n = 7; for (int i = 0; i < n - 1; i++) { var typeA = types[i]; for (int j = i + 1; j < n; j++) { var typeB = types[j]; bool expectedEqual = (i == 5) && (j == 6); Assert.Equal(TypeSymbol.Equals(typeA, typeB, TypeCompareKind.ConsiderEverything2), expectedEqual); } } } [WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")] [Fact] public void ErrorInfo_01() { var error = new MissingMetadataTypeSymbol.Nested(new UnsupportedMetadataTypeSymbol(), "Test", 0, false); var info = error.ErrorInfo; Assert.Equal(ErrorCode.ERR_BogusType, (ErrorCode)info.Code); Assert.Null(error.ContainingModule); Assert.Null(error.ContainingAssembly); Assert.NotNull(error.ContainingSymbol); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Tools/ExternalAccess/OmniSharp/Structure/OmniSharpBlockSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure { internal readonly struct OmniSharpBlockSpan { private const string Ellipses = "..."; /// <summary> /// Whether or not this span can be collapsed. /// </summary> public bool IsCollapsible { get; } /// <summary> /// The span of text to collapse. /// </summary> public TextSpan TextSpan { get; } /// <summary> /// The span of text to display in the hint on mouse hover. /// </summary> public TextSpan HintSpan { get; } /// <summary> /// The text to display inside the collapsed region. /// </summary> public string BannerText { get; } /// <summary> /// Whether or not this region should be automatically collapsed when the 'Collapse to Definitions' command is invoked. /// </summary> public bool AutoCollapse { get; } /// <summary> /// Whether this region should be collapsed by default when a file is opened the first time. /// </summary> public bool IsDefaultCollapsed { get; } public string Type { get; } public OmniSharpBlockSpan( string type, bool isCollapsible, TextSpan textSpan, string bannerText = Ellipses, bool autoCollapse = false, bool isDefaultCollapsed = false) : this(type, isCollapsible, textSpan, textSpan, bannerText, autoCollapse, isDefaultCollapsed) { } public OmniSharpBlockSpan( string type, bool isCollapsible, TextSpan textSpan, TextSpan hintSpan, string bannerText = Ellipses, bool autoCollapse = false, bool isDefaultCollapsed = false) { TextSpan = textSpan; BannerText = bannerText; HintSpan = hintSpan; AutoCollapse = autoCollapse; IsDefaultCollapsed = isDefaultCollapsed; IsCollapsible = isCollapsible; Type = type; } public override string ToString() { return this.TextSpan != this.HintSpan ? $"{{Span={TextSpan}, HintSpan={HintSpan}, BannerText=\"{BannerText}\", AutoCollapse={AutoCollapse}, IsDefaultCollapsed={IsDefaultCollapsed}}}" : $"{{Span={TextSpan}, BannerText=\"{BannerText}\", AutoCollapse={AutoCollapse}, IsDefaultCollapsed={IsDefaultCollapsed}}}"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure { internal readonly struct OmniSharpBlockSpan { private const string Ellipses = "..."; /// <summary> /// Whether or not this span can be collapsed. /// </summary> public bool IsCollapsible { get; } /// <summary> /// The span of text to collapse. /// </summary> public TextSpan TextSpan { get; } /// <summary> /// The span of text to display in the hint on mouse hover. /// </summary> public TextSpan HintSpan { get; } /// <summary> /// The text to display inside the collapsed region. /// </summary> public string BannerText { get; } /// <summary> /// Whether or not this region should be automatically collapsed when the 'Collapse to Definitions' command is invoked. /// </summary> public bool AutoCollapse { get; } /// <summary> /// Whether this region should be collapsed by default when a file is opened the first time. /// </summary> public bool IsDefaultCollapsed { get; } public string Type { get; } public OmniSharpBlockSpan( string type, bool isCollapsible, TextSpan textSpan, string bannerText = Ellipses, bool autoCollapse = false, bool isDefaultCollapsed = false) : this(type, isCollapsible, textSpan, textSpan, bannerText, autoCollapse, isDefaultCollapsed) { } public OmniSharpBlockSpan( string type, bool isCollapsible, TextSpan textSpan, TextSpan hintSpan, string bannerText = Ellipses, bool autoCollapse = false, bool isDefaultCollapsed = false) { TextSpan = textSpan; BannerText = bannerText; HintSpan = hintSpan; AutoCollapse = autoCollapse; IsDefaultCollapsed = isDefaultCollapsed; IsCollapsible = isCollapsible; Type = type; } public override string ToString() { return this.TextSpan != this.HintSpan ? $"{{Span={TextSpan}, HintSpan={HintSpan}, BannerText=\"{BannerText}\", AutoCollapse={AutoCollapse}, IsDefaultCollapsed={IsDefaultCollapsed}}}" : $"{{Span={TextSpan}, BannerText=\"{BannerText}\", AutoCollapse={AutoCollapse}, IsDefaultCollapsed={IsDefaultCollapsed}}}"; } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/VisualBasic/Portable/Scanner/ScannerBuffer.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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Imports System.Text Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner ''' <summary> ''' page represents a cached array of chars. ''' </summary> Private Class Page ''' <summary> ''' where page maps in the stream. Used to validate pages ''' </summary> Friend _pageStart As Integer ''' <summary> ''' page's buffer ''' </summary> Friend ReadOnly _arr As Char() Private ReadOnly _pool As ObjectPool(Of Page) Private Sub New(pool As ObjectPool(Of Page)) _pageStart = -1 _arr = New Char(s_PAGE_SIZE - 1) {} _pool = pool End Sub Friend Sub Free() _pageStart = -1 _pool.Free(Me) End Sub Private Shared ReadOnly s_poolInstance As ObjectPool(Of Page) = CreatePool() Private Shared Function CreatePool() As ObjectPool(Of Page) Dim pool As ObjectPool(Of Page) = Nothing pool = New ObjectPool(Of Page)(Function() New Page(pool), 128) Return pool End Function Friend Shared Function GetInstance() As Page Dim instance = s_poolInstance.Allocate() Return instance End Function End Class ''' <summary> ''' current page we are reading. ''' </summary> Private _curPage As Page Private ReadOnly _pages(s_PAGE_NUM - 1) As Page Private Const s_PAGE_NUM_SHIFT = 2 Private Const s_PAGE_NUM = CInt(2 ^ s_PAGE_NUM_SHIFT) Private Const s_PAGE_NUM_MASK = s_PAGE_NUM - 1 Private Const s_PAGE_SHIFT = 11 Private Const s_PAGE_SIZE = CInt(2 ^ s_PAGE_SHIFT) Private Const s_PAGE_MASK = s_PAGE_SIZE - 1 Private Const s_NOT_PAGE_MASK = Not s_PAGE_MASK Private ReadOnly _buffer As SourceText Private ReadOnly _bufferLen As Integer ' created on demand. we may not need it Private _builder As StringBuilder ''' <summary> ''' gets a page for the position. ''' will initialize it if we have cache miss ''' </summary> Private Function GetPage(position As Integer) As Page Dim pageNum = (position >> s_PAGE_SHIFT) And s_PAGE_NUM_MASK Dim p = _pages(pageNum) Dim pageStart = position And s_NOT_PAGE_MASK If p Is Nothing Then p = Page.GetInstance _pages(pageNum) = p End If If p._pageStart <> pageStart Then _buffer.CopyTo(pageStart, p._arr, 0, Math.Min(_bufferLen - pageStart, s_PAGE_SIZE)) p._pageStart = pageStart End If _curPage = p Return p End Function ' PERF CRITICAL Private Function Peek(skip As Integer) As Char Debug.Assert(CanGet(skip)) Debug.Assert(skip >= -MaxCharsLookBehind) Dim position = _lineBufferOffset Dim page = _curPage position += skip Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function ' PERF CRITICAL Friend Function Peek() As Char Dim page = _curPage Dim position = _lineBufferOffset Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function Friend Function GetChar() As String Return Intern(Peek()) End Function Friend Function GetText(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Return Intern(page._arr, offsetInPage, length) End If Return GetTextSlow(start, length) End Function Friend Function GetTextNotInterned(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Dim arr() As Char = page._arr ' Always intern CR+LF since it occurs so frequently If length = 2 AndAlso arr(offsetInPage) = ChrW(13) AndAlso arr(offsetInPage + 1) = ChrW(10) Then Return vbCrLf End If Return New String(arr, offsetInPage, length) End If Return GetTextSlow(start, length, suppressInterning:=True) End Function Private Function GetTextSlow(start As Integer, length As Integer, Optional suppressInterning As Boolean = False) As String Dim textOffset = start And s_PAGE_MASK Dim page = GetPage(start) If textOffset + length < s_PAGE_SIZE Then If suppressInterning Then Return New String(page._arr, textOffset, length) Else Return Intern(page._arr, textOffset, length) End If End If ' make a string builder that is big enough, but not too big If _builder Is Nothing Then _builder = New StringBuilder(Math.Min(length, 1024)) End If Dim cnt = Math.Min(length, s_PAGE_SIZE - textOffset) _builder.Append(page._arr, textOffset, cnt) Dim dst = cnt length -= cnt start += cnt Do page = GetPage(start) cnt = Math.Min(length, s_PAGE_SIZE) _builder.Append(page._arr, 0, cnt) dst += cnt length -= cnt start += cnt Loop While length > 0 Dim result As String If suppressInterning Then result = _builder.ToString Else result = _stringTable.Add(_builder) End If If result.Length < 1024 Then _builder.Clear() Else _builder = Nothing End If Return result 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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Imports System.Text Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner ''' <summary> ''' page represents a cached array of chars. ''' </summary> Private Class Page ''' <summary> ''' where page maps in the stream. Used to validate pages ''' </summary> Friend _pageStart As Integer ''' <summary> ''' page's buffer ''' </summary> Friend ReadOnly _arr As Char() Private ReadOnly _pool As ObjectPool(Of Page) Private Sub New(pool As ObjectPool(Of Page)) _pageStart = -1 _arr = New Char(s_PAGE_SIZE - 1) {} _pool = pool End Sub Friend Sub Free() _pageStart = -1 _pool.Free(Me) End Sub Private Shared ReadOnly s_poolInstance As ObjectPool(Of Page) = CreatePool() Private Shared Function CreatePool() As ObjectPool(Of Page) Dim pool As ObjectPool(Of Page) = Nothing pool = New ObjectPool(Of Page)(Function() New Page(pool), 128) Return pool End Function Friend Shared Function GetInstance() As Page Dim instance = s_poolInstance.Allocate() Return instance End Function End Class ''' <summary> ''' current page we are reading. ''' </summary> Private _curPage As Page Private ReadOnly _pages(s_PAGE_NUM - 1) As Page Private Const s_PAGE_NUM_SHIFT = 2 Private Const s_PAGE_NUM = CInt(2 ^ s_PAGE_NUM_SHIFT) Private Const s_PAGE_NUM_MASK = s_PAGE_NUM - 1 Private Const s_PAGE_SHIFT = 11 Private Const s_PAGE_SIZE = CInt(2 ^ s_PAGE_SHIFT) Private Const s_PAGE_MASK = s_PAGE_SIZE - 1 Private Const s_NOT_PAGE_MASK = Not s_PAGE_MASK Private ReadOnly _buffer As SourceText Private ReadOnly _bufferLen As Integer ' created on demand. we may not need it Private _builder As StringBuilder ''' <summary> ''' gets a page for the position. ''' will initialize it if we have cache miss ''' </summary> Private Function GetPage(position As Integer) As Page Dim pageNum = (position >> s_PAGE_SHIFT) And s_PAGE_NUM_MASK Dim p = _pages(pageNum) Dim pageStart = position And s_NOT_PAGE_MASK If p Is Nothing Then p = Page.GetInstance _pages(pageNum) = p End If If p._pageStart <> pageStart Then _buffer.CopyTo(pageStart, p._arr, 0, Math.Min(_bufferLen - pageStart, s_PAGE_SIZE)) p._pageStart = pageStart End If _curPage = p Return p End Function ' PERF CRITICAL Private Function Peek(skip As Integer) As Char Debug.Assert(CanGet(skip)) Debug.Assert(skip >= -MaxCharsLookBehind) Dim position = _lineBufferOffset Dim page = _curPage position += skip Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function ' PERF CRITICAL Friend Function Peek() As Char Dim page = _curPage Dim position = _lineBufferOffset Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function Friend Function GetChar() As String Return Intern(Peek()) End Function Friend Function GetText(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Return Intern(page._arr, offsetInPage, length) End If Return GetTextSlow(start, length) End Function Friend Function GetTextNotInterned(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Dim arr() As Char = page._arr ' Always intern CR+LF since it occurs so frequently If length = 2 AndAlso arr(offsetInPage) = ChrW(13) AndAlso arr(offsetInPage + 1) = ChrW(10) Then Return vbCrLf End If Return New String(arr, offsetInPage, length) End If Return GetTextSlow(start, length, suppressInterning:=True) End Function Private Function GetTextSlow(start As Integer, length As Integer, Optional suppressInterning As Boolean = False) As String Dim textOffset = start And s_PAGE_MASK Dim page = GetPage(start) If textOffset + length < s_PAGE_SIZE Then If suppressInterning Then Return New String(page._arr, textOffset, length) Else Return Intern(page._arr, textOffset, length) End If End If ' make a string builder that is big enough, but not too big If _builder Is Nothing Then _builder = New StringBuilder(Math.Min(length, 1024)) End If Dim cnt = Math.Min(length, s_PAGE_SIZE - textOffset) _builder.Append(page._arr, textOffset, cnt) Dim dst = cnt length -= cnt start += cnt Do page = GetPage(start) cnt = Math.Min(length, s_PAGE_SIZE) _builder.Append(page._arr, 0, cnt) dst += cnt length -= cnt start += cnt Loop While length > 0 Dim result As String If suppressInterning Then result = _builder.ToString Else result = _stringTable.Add(_builder) End If If result.Length < 1024 Then _builder.Clear() Else _builder = Nothing End If Return result End Function End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests5.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PatternMatchingTests5 : PatternMatchingTestBase { [Fact] public void ExtendedPropertyPatterns_01() { var program = @" using System; class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public C Prop3 { get; set; } static bool Test1(C o) => o is { Prop1.Prop2.Prop3: null }; static bool Test2(S o) => o is { Prop1.Prop2.Prop3: null }; static bool Test3(S? o) => o is { Prop1.Prop2.Prop3: null }; static bool Test4(S0 o) => o is { Prop1.Prop2.Prop3: 420 }; public static void Main() { Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test1(new() { Prop1 = null })); Console.WriteLine(Test2(new() { Prop1 = null })); Console.WriteLine(Test3(new() { Prop1 = null })); Console.WriteLine(Test1(default)); Console.WriteLine(Test2(default)); Console.WriteLine(Test3(default)); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 421 }}})); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 420 }}})); } } struct S { public A? Prop1; } struct A { public B? Prop2; } struct B { public int? Prop3; } struct S0 { public A0 Prop1; } struct A0 { public B0 Prop2; } struct B0 { public int Prop3; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" True True True False False False False False False False False False False True "; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (C V_0, C V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0021 IL_0003: ldarg.0 IL_0004: callvirt ""C C.Prop1.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0021 IL_000d: ldloc.0 IL_000e: callvirt ""C C.Prop2.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop3.get"" IL_001d: ldnull IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret }"); verifier.VerifyIL("C.Test2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (A? V_0, B? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: ldfld ""A? S.Prop1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""bool A?.HasValue.get"" IL_000e: brfalse.s IL_003e IL_0010: ldloca.s V_0 IL_0012: call ""A A?.GetValueOrDefault()"" IL_0017: ldfld ""B? A.Prop2"" IL_001c: stloc.1 IL_001d: ldloca.s V_1 IL_001f: call ""bool B?.HasValue.get"" IL_0024: brfalse.s IL_003e IL_0026: ldloca.s V_1 IL_0028: call ""B B?.GetValueOrDefault()"" IL_002d: ldfld ""int? B.Prop3"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool int?.HasValue.get"" IL_003a: ldc.i4.0 IL_003b: ceq IL_003d: ret IL_003e: ldc.i4.0 IL_003f: ret }"); verifier.VerifyIL("C.Test4", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""A0 S0.Prop1"" IL_0006: ldfld ""B0 A0.Prop2"" IL_000b: ldfld ""int B0.Prop3"" IL_0010: ldc.i4 0x1a4 IL_0015: ceq IL_0017: ret }"); } [Fact] public void ExtendedPropertyPatterns_02() { var program = @" class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public static void Main() { _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; _ = new C() is { Prop1: null, Prop1.Prop2: null }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (9,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null } and { Prop1.Prop2: null }").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null, Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null, Prop1.Prop2: null }").WithArguments("C").WithLocation(10, 13) ); } [Fact] public void ExtendedPropertyPatterns_03() { var program = @" using System; class C { C _prop1; C _prop2; C Prop1 { get { Console.WriteLine(nameof(Prop1)); return _prop1; } set => _prop1 = value; } C Prop2 { get { Console.WriteLine(nameof(Prop2)); return _prop2; } set => _prop2 = value; } public static void Main() { Test(null); Test(new()); Test(new() { Prop1 = new() }); Test(new() { Prop1 = new() { Prop2 = new() } }); } static void Test(C o) { Console.WriteLine(nameof(Test)); var result = o switch { {Prop1: null} => 1, {Prop1.Prop2: null} => 2, _ => -1, }; Console.WriteLine(result); } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" Test -1 Test Prop1 1 Test Prop1 Prop2 2 Test Prop1 Prop2 -1"; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, C V_1) IL_0000: ldstr ""Test"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldarg.0 IL_000b: brfalse.s IL_0029 IL_000d: ldarg.0 IL_000e: callvirt ""C C.Prop1.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop2.get"" IL_001d: brfalse.s IL_0025 IL_001f: br.s IL_0029 IL_0021: ldc.i4.1 IL_0022: stloc.0 IL_0023: br.s IL_002b IL_0025: ldc.i4.2 IL_0026: stloc.0 IL_0027: br.s IL_002b IL_0029: ldc.i4.m1 IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ExtendedPropertyPatterns_04() { var program = @" class C { public static void Main() { _ = new C() is { Prop1<int>.Prop2: {} }; _ = new C() is { Prop1->Prop2: {} }; _ = new C() is { Prop1!.Prop2: {} }; _ = new C() is { Prop1?.Prop2: {} }; _ = new C() is { Prop1[0]: {} }; _ = new C() is { 1: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1<int>.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1<int>").WithLocation(6, 26), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1->Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1->Prop2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1!.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1!").WithLocation(8, 26), // (9,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1?.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1?.Prop2").WithLocation(9, 26), // (10,26): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop1[0] }' // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop1[0]").WithArguments("Prop1[0]").WithLocation(10, 26), // (10,26): error CS0246: The type or namespace name 'Prop1' could not be found (are you missing a using directive or an assembly reference?) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop1").WithArguments("Prop1").WithLocation(10, 26), // (10,31): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[0]").WithLocation(10, 31), // (10,34): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(10, 34), // (10,36): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(10, 36), // (11,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { 1: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "1").WithLocation(11, 26)); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1.Field2.Field3: {} }; _ = this is { Field4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_NestedRecursivePattern() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1: { Field2.Field3.Field4: not null } }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_Properties() { var program = @" class C { C Prop1 { get; set; } C Prop2 { get; set; } C Prop3 { get; set; } C Prop4 { get; set; } public void M() { _ = this is { Prop1.Prop2.Prop3: {} }; _ = this is { Prop4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics(); } [Fact] public void ExtendedPropertyPatterns_IOperation_Properties() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Prop1.Prop2.Prop3: null }; }/*</bind>*/ } class A { public B Prop1 => null; } class B { public C Prop2 => null; } class C { public object Prop3 => null; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... p3: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... op3: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, DiagnosticDescription.None, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_IOperation_FieldsInStructs() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Field1.Field2.Field3: null, Field4: null }; }/*</bind>*/ } struct A { public B? Field1; public B? Field4; } struct B { public C? Field2; } struct C { public object Field3; } "; var expectedDiagnostics = new[] { // (9,22): warning CS0649: Field 'A.Field1' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("A.Field1", "").WithLocation(9, 22), // (9,40): warning CS0649: Field 'A.Field4' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("A.Field4", "").WithLocation(9, 40), // (10,22): warning CS0649: Field 'B.Field2' is never assigned to, and will always have its default value // struct B { public C? Field2; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("B.Field2", "").WithLocation(10, 22), // (11,26): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // struct C { public object Field3; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(11, 26) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(expectedDiagnostics); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... d4: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... ld4: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_Explainer() { var src = @" class Program { void M(A a) { _ = a switch // 1 { { BProp.BoolProp: true } => 1 }; _ = a switch // 2 { { BProp.IntProp: <= 0 } => 1 }; } } class A { public B BProp => null; } class B { public bool BoolProp => true; public int IntProp => 0; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { BoolProp: false } }' is not covered. // _ = a switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { BoolProp: false } }").WithLocation(6, 15), // (11,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { IntProp: 1 } }' is not covered. // _ = a switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { IntProp: 1 } }").WithLocation(11, 15) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_BadMemberAccess() { var program = @" class C { C Field1, Field2, Field3; public static void Main() { _ = new C() is { Field1?.Field2: {} }; // 1 _ = new C() is { Field1!.Field2: {} }; // 2 _ = new C() is { Missing: null }; // 3 _ = new C() is { Field3.Missing: {} }; // 4 _ = new C() is { Missing1.Missing2: {} }; // 5 } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0169: The field 'C.Field1' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("C.Field1").WithLocation(4, 7), // (4,15): warning CS0169: The field 'C.Field2' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field2").WithArguments("C.Field2").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1?.Field2: {} }; // 1 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1?.Field2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1!.Field2: {} }; // 2 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1!").WithLocation(8, 26), // (9,26): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Missing: null }; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(9, 26), // (10,33): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Field3.Missing: {} }; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(10, 33), // (11,26): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = new C() is { Missing1.Missing2: {} }; // 5 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(11, 26) ); } [Fact] public void ExtendedPropertyPatterns_IOperationOnMissing() { var program = @" class C { public void M() { _ = this is { Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing' // _ = this is { Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Missing: null') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnNestedMissing() { var program = @" class C { int Property { get; set; } public void M() { _ = this is { Property.Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (7,32): error CS0117: 'int' does not contain a definition for 'Missing' // _ = this is { Property.Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("int", "Missing").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { P ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Property. ... ing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Property') Member: IPropertyReferenceOperation: System.Int32 C.Property { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Property') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Property') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Property') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: null, MatchedType: System.Int32, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Property.Missing') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Property.Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnTwoMissing() { var program = @" class C { public void M() { _ = this is { Missing1.Missing2: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = this is { Missing1.Missing2: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ng2: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing1. ... ng2: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1.Missing2') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1.Missing2') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_SuppressionOnPattern() { var program = @" #nullable enable public class ContainerType { public class Type { public void M() { const Type c = null!; if (this is c!) {} if (this is (c!)) {} if (this is Type!) {} // 1 if (this is ContainerType!.Type) {} // 2 if (this is ContainerType.Type!) {} // 3 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (12,25): error CS8598: The suppression operator is not allowed in this context // if (this is Type!) {} // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "Type!").WithLocation(12, 25), // (13,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType!.Type) {} // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType").WithLocation(13, 25), // (14,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType.Type!) {} // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType.Type!").WithLocation(14, 25) ); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_PointerAccessInPattern() { var program = @" public class Type { public unsafe void M(S* s) { if (0 is s->X) {} } } public struct S { public int X; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.UnsafeDebugDll); compilation.VerifyEmitDiagnostics( // (6,18): error CS0150: A constant value is expected // if (0 is s->X) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "s->X").WithLocation(6, 18) ); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_01() { var source = @" using System; class Program { public static void Main() { P p = new P(); Console.WriteLine(p is { X.Y: {}, Y.X: {} }); } } class P { public P X { get; } public P Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (14,14): warning CS0649: Field 'P.Y' is never assigned to, and will always have its default value null // public P Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("P.Y", "null").WithLocation(14, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("P P.Y", xySymbol.Symbol.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("P P.Y", yNameSymbol.Symbol.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("P P.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("P P.Y", ySymbol.Symbol.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_02() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } interface I1 { P X { get; } P Y { get; } } interface I2 { P X { get; } P Y { get; } } interface P : I1, I2 { // X and Y inherited ambiguously } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0229: Ambiguity between 'I1.X' and 'I2.X' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "X").WithArguments("I1.X", "I2.X").WithLocation(8, 34), // (8,43): error CS0229: Ambiguity between 'I1.Y' and 'I2.Y' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "Y").WithArguments("I1.Y", "I2.Y").WithLocation(8, 43) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.Ambiguous, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Equal(2, xSymbol.CandidateSymbols.Length); Assert.Equal("P I1.X { get; }", xSymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.X { get; }", xSymbol.CandidateSymbols[1].ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.Ambiguous, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Equal(2, ySymbol.CandidateSymbols.Length); Assert.Equal("P I1.Y { get; }", ySymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.Y { get; }", ySymbol.CandidateSymbols[1].ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_03() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } class P { } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0117: 'P' does not contain a definition for 'X' // Console.WriteLine(p is { X: 3, Y: 4 }); Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("P", "X").WithLocation(8, 34) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = subpatterns[0].ExpressionColon.Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Empty(xSymbol.CandidateSymbols); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = subpatterns[1].ExpressionColon.Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Empty(ySymbol.CandidateSymbols); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_04() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(new C() is { X.Y: {} }); Console.WriteLine(new S() is { Y.X: {} }); } } class C { public S? X { get; } } struct S { public C Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (17,14): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value null // public C Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "null").WithLocation(17, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("C S.Y", xySymbol.Symbol.ToTestDisplayString()); var xyType = model.GetTypeInfo(xy); Assert.Equal("C", xyType.Type.ToTestDisplayString()); Assert.Equal("C", xyType.ConvertedType.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var xType = model.GetTypeInfo(x); Assert.Equal("S?", xType.Type.ToTestDisplayString()); Assert.Equal("S?", xType.ConvertedType.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("C S.Y", yNameSymbol.Symbol.ToTestDisplayString()); var yNameType = model.GetTypeInfo(yName); Assert.Equal("C", yNameType.Type.ToTestDisplayString()); Assert.Equal("C", yNameType.ConvertedType.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var yxType = model.GetTypeInfo(yx); Assert.Equal("S?", yxType.Type.ToTestDisplayString()); Assert.Equal("S?", yxType.ConvertedType.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("C S.Y", ySymbol.Symbol.ToTestDisplayString()); var yType = model.GetTypeInfo(y); Assert.Equal("C", yType.Type.ToTestDisplayString()); Assert.Equal("C", yType.ConvertedType.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); var xNameType = model.GetTypeInfo(xName); Assert.Equal("S?", xNameType.Type.ToTestDisplayString()); Assert.Equal("S?", xNameType.ConvertedType.ToTestDisplayString()); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("Program.Main", @" { // Code size 92 (0x5c) .maxstack 2 .locals init (C V_0, S? V_1, S V_2) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_002b IL_000a: ldloc.0 IL_000b: callvirt ""S? C.X.get"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: call ""bool S?.HasValue.get"" IL_0018: brfalse.s IL_002b IL_001a: ldloca.s V_1 IL_001c: call ""S S?.GetValueOrDefault()"" IL_0021: ldfld ""C S.Y"" IL_0026: ldnull IL_0027: cgt.un IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: call ""void System.Console.WriteLine(bool)"" IL_0031: nop IL_0032: ldloca.s V_2 IL_0034: initobj ""S"" IL_003a: ldloc.2 IL_003b: ldfld ""C S.Y"" IL_0040: stloc.0 IL_0041: ldloc.0 IL_0042: brfalse.s IL_0054 IL_0044: ldloc.0 IL_0045: callvirt ""S? C.X.get"" IL_004a: stloc.1 IL_004b: ldloca.s V_1 IL_004d: call ""bool S?.HasValue.get"" IL_0052: br.s IL_0055 IL_0054: ldc.i4.0 IL_0055: call ""void System.Console.WriteLine(bool)"" IL_005a: nop IL_005b: ret } "); } [Fact] public void ExtendedPropertyPatterns_Nullability_Properties() { var program = @" #nullable enable class C { C? Prop { get; } public void M() { if (this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 1 } if (this is { Prop.Prop: {} }) { this.Prop.ToString(); this.Prop.Prop.ToString(); } if (this is { Prop: null } && this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 2 } if (this is { Prop: null } || this is { Prop.Prop: null }) { this.Prop.ToString(); // 3 this.Prop.Prop.ToString(); // 4 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(9, 13), // (20,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(20, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(26, 13)); } [Fact] public void ExtendedPropertyPatterns_Nullability_AnnotatedFields() { var program = @" #nullable enable class C { public void M(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); // 4 } } } class C1 { public C2? Prop1 = null; } class C2 { public object? Prop2 = null; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(8, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(25, 13) ); } [Fact] public void ExtendedPropertyPatterns_Nullability_UnannotatedFields() { var program = @" #nullable enable class C { public void M1(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M2(C1 c1) { if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M3(C1 c1) { if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } else { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); } } public void M4(C1 c1) { if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 4 c1.Prop1.Prop2.ToString(); // 5 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } } class C1 { public C2 Prop1 = null!; } class C2 { public object Prop2 = null!; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(34, 13), // (38,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(38, 13), // (48,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(48, 13), // (49,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(49, 13) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInPositionalPattern() { var source = @" class C { C Property { get; set; } void M() { _ = this is (Property.Property: null, Property: null); } public void Deconstruct(out C c1, out C c2) => throw null; } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyEmitDiagnostics( // (8,22): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property.Property").WithArguments("extended property patterns", "10.0").WithLocation(8, 22), // (8,22): error CS1001: Identifier expected // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Property.Property").WithLocation(8, 22), // (8,47): error CS8517: The name 'Property' does not match the corresponding 'Deconstruct' parameter 'c2'. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "Property").WithArguments("Property", "c2").WithLocation(8, 47) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInITuplePattern() { var source = @" class C { void M() { System.Runtime.CompilerServices.ITuple t = null; var r = t is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,23): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(7, 23), // (7,31): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(7, 31) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInValueTuplePattern() { var source = @" class C { void M() { _ = (1, 2) is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (6,24): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(6, 24), // (6,32): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(6, 32) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { [ObsoleteAttribute(""error Prop1"", true)] public C2 Prop1 { get; set; } } class C2 { [ObsoleteAttribute(""error Prop2"", true)] public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1").WithArguments("C1.Prop1", "error Prop1").WithLocation(7, 21), // (7,27): error CS0619: 'C2.Prop2' is obsolete: 'error Prop2' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop2").WithArguments("C2.Prop2", "error Prop2").WithLocation(7, 27) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteAccessor() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { [ObsoleteAttribute(""error Prop1"", true)] get; set; } } class C2 { public object Prop2 { get; [ObsoleteAttribute(""error Prop2"", true)] set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1.get' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1.Prop2").WithArguments("C1.Prop1.get", "error Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_InaccessibleProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { private C2 Prop1 { get; set; } } class C2 { private object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0122: 'C1.Prop1' is inaccessible due to its protection level // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_BadAccess, "Prop1").WithArguments("C1.Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionTree() { var program = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { public void M1(C1 c1) { Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { get; set; } } class C2 { public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,48): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "c1 is { Prop1.Prop2: null }").WithLocation(9, 48) ); } [Fact] public void ExtendedPropertyPatterns_EvaluationOrder() { var program = @" if (new C() is { Prop1.True: true, Prop1.Prop2: not null }) { System.Console.WriteLine(""matched1""); } if (new C() is { Prop1.Prop2: not null, Prop1.True: true }) { System.Console.WriteLine(""matched2""); } if (new C() is { Prop1.Prop2: not null, Prop2.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1.Prop2.Prop3.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1: { Prop2.Prop3.True: true } }) { System.Console.WriteLine(""matched4""); } if (new C() is { Prop1.True: false, Prop1.Prop2: not null }) { throw null; } class C { public C Prop1 { get { System.Console.Write(""Prop1 ""); return this; } } public C Prop2 { get { System.Console.Write(""Prop2 ""); return this; } } public C Prop3 { get { System.Console.Write(""Prop3 ""); return this; } } public bool True { get { System.Console.Write(""True ""); return true; } } } "; CompileAndVerify(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, expectedOutput: @" Prop1 True Prop2 matched1 Prop1 Prop2 True matched2 Prop1 Prop2 Prop2 True matched3 Prop1 Prop2 Prop3 True matched3 Prop1 Prop2 Prop3 True matched4 Prop1 True"); } [Fact] public void ExtendedPropertyPatterns_StaticMembers() { var program = @" _ = new C() is { Static: null }; // 1 _ = new C() is { Instance.Static: null }; // 2 _ = new C() is { Static.Instance: null }; // 3 class C { public C Instance { get; set; } public static C Static { get; set; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static: null }; // 1 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(2, 18), // (3,27): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Instance.Static: null }; // 2 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(3, 27), // (4,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static.Instance: null }; // 3 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(4, 18) ); } [Fact] public void ExtendedPropertyPatterns_Exhaustiveness() { var program = @" _ = new C() switch // 1 { { Prop.True: true } => 0 }; _ = new C() switch { { Prop.True: true } => 0, { Prop.True: false } => 0 }; #nullable enable _ = new C() switch // 2 { { Prop.Prop: null } => 0 }; class C { public C Prop { get => throw null!; } public bool True { get => throw null!; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { True: false } }' is not covered. // _ = new C() switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { True: false } }").WithLocation(2, 13), // (14,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { Prop: not null } }' is not covered. // _ = new C() switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { Prop: not null } }").WithLocation(14, 13) ); } [Fact, WorkItem(55184, "https://github.com/dotnet/roslyn/issues/55184")] public void Repro55184() { var source = @" var x = """"; _ = x is { Error: { Length: > 0 } }; _ = x is { Error.Length: > 0 }; _ = x is { Length: { Error: > 0 } }; _ = x is { Length.Error: > 0 }; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error: { Length: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(4, 12), // (5,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error.Length: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(5, 12), // (6,22): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length: { Error: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(6, 22), // (7,19): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length.Error: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(7, 19) ); } public class FlowAnalysisTests : FlowTestBase { [Fact] public void RegionInIsPattern01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(object o) { _ = o switch { string { Length: 0 } s => /*<bind>*/s.ToString()/*</bind>*/, _ = throw null }; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("o, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.UnsafeAddressTaken)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PatternMatchingTests5 : PatternMatchingTestBase { [Fact] public void ExtendedPropertyPatterns_01() { var program = @" using System; class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public C Prop3 { get; set; } static bool Test1(C o) => o is { Prop1.Prop2.Prop3: null }; static bool Test2(S o) => o is { Prop1.Prop2.Prop3: null }; static bool Test3(S? o) => o is { Prop1.Prop2.Prop3: null }; static bool Test4(S0 o) => o is { Prop1.Prop2.Prop3: 420 }; public static void Main() { Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test1(new() { Prop1 = null })); Console.WriteLine(Test2(new() { Prop1 = null })); Console.WriteLine(Test3(new() { Prop1 = null })); Console.WriteLine(Test1(default)); Console.WriteLine(Test2(default)); Console.WriteLine(Test3(default)); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 421 }}})); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 420 }}})); } } struct S { public A? Prop1; } struct A { public B? Prop2; } struct B { public int? Prop3; } struct S0 { public A0 Prop1; } struct A0 { public B0 Prop2; } struct B0 { public int Prop3; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" True True True False False False False False False False False False False True "; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (C V_0, C V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0021 IL_0003: ldarg.0 IL_0004: callvirt ""C C.Prop1.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0021 IL_000d: ldloc.0 IL_000e: callvirt ""C C.Prop2.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop3.get"" IL_001d: ldnull IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret }"); verifier.VerifyIL("C.Test2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (A? V_0, B? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: ldfld ""A? S.Prop1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""bool A?.HasValue.get"" IL_000e: brfalse.s IL_003e IL_0010: ldloca.s V_0 IL_0012: call ""A A?.GetValueOrDefault()"" IL_0017: ldfld ""B? A.Prop2"" IL_001c: stloc.1 IL_001d: ldloca.s V_1 IL_001f: call ""bool B?.HasValue.get"" IL_0024: brfalse.s IL_003e IL_0026: ldloca.s V_1 IL_0028: call ""B B?.GetValueOrDefault()"" IL_002d: ldfld ""int? B.Prop3"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool int?.HasValue.get"" IL_003a: ldc.i4.0 IL_003b: ceq IL_003d: ret IL_003e: ldc.i4.0 IL_003f: ret }"); verifier.VerifyIL("C.Test4", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""A0 S0.Prop1"" IL_0006: ldfld ""B0 A0.Prop2"" IL_000b: ldfld ""int B0.Prop3"" IL_0010: ldc.i4 0x1a4 IL_0015: ceq IL_0017: ret }"); } [Fact] public void ExtendedPropertyPatterns_02() { var program = @" class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public static void Main() { _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; _ = new C() is { Prop1: null, Prop1.Prop2: null }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (9,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null } and { Prop1.Prop2: null }").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null, Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null, Prop1.Prop2: null }").WithArguments("C").WithLocation(10, 13) ); } [Fact] public void ExtendedPropertyPatterns_03() { var program = @" using System; class C { C _prop1; C _prop2; C Prop1 { get { Console.WriteLine(nameof(Prop1)); return _prop1; } set => _prop1 = value; } C Prop2 { get { Console.WriteLine(nameof(Prop2)); return _prop2; } set => _prop2 = value; } public static void Main() { Test(null); Test(new()); Test(new() { Prop1 = new() }); Test(new() { Prop1 = new() { Prop2 = new() } }); } static void Test(C o) { Console.WriteLine(nameof(Test)); var result = o switch { {Prop1: null} => 1, {Prop1.Prop2: null} => 2, _ => -1, }; Console.WriteLine(result); } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" Test -1 Test Prop1 1 Test Prop1 Prop2 2 Test Prop1 Prop2 -1"; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, C V_1) IL_0000: ldstr ""Test"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldarg.0 IL_000b: brfalse.s IL_0029 IL_000d: ldarg.0 IL_000e: callvirt ""C C.Prop1.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop2.get"" IL_001d: brfalse.s IL_0025 IL_001f: br.s IL_0029 IL_0021: ldc.i4.1 IL_0022: stloc.0 IL_0023: br.s IL_002b IL_0025: ldc.i4.2 IL_0026: stloc.0 IL_0027: br.s IL_002b IL_0029: ldc.i4.m1 IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ExtendedPropertyPatterns_04() { var program = @" class C { public static void Main() { _ = new C() is { Prop1<int>.Prop2: {} }; _ = new C() is { Prop1->Prop2: {} }; _ = new C() is { Prop1!.Prop2: {} }; _ = new C() is { Prop1?.Prop2: {} }; _ = new C() is { Prop1[0]: {} }; _ = new C() is { 1: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1<int>.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1<int>").WithLocation(6, 26), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1->Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1->Prop2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1!.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1!").WithLocation(8, 26), // (9,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1?.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1?.Prop2").WithLocation(9, 26), // (10,26): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop1[0] }' // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop1[0]").WithArguments("Prop1[0]").WithLocation(10, 26), // (10,26): error CS0246: The type or namespace name 'Prop1' could not be found (are you missing a using directive or an assembly reference?) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop1").WithArguments("Prop1").WithLocation(10, 26), // (10,31): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[0]").WithLocation(10, 31), // (10,34): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(10, 34), // (10,36): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(10, 36), // (11,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { 1: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "1").WithLocation(11, 26)); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1.Field2.Field3: {} }; _ = this is { Field4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_NestedRecursivePattern() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1: { Field2.Field3.Field4: not null } }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_Properties() { var program = @" class C { C Prop1 { get; set; } C Prop2 { get; set; } C Prop3 { get; set; } C Prop4 { get; set; } public void M() { _ = this is { Prop1.Prop2.Prop3: {} }; _ = this is { Prop4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics(); } [Fact] public void ExtendedPropertyPatterns_IOperation_Properties() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Prop1.Prop2.Prop3: null }; }/*</bind>*/ } class A { public B Prop1 => null; } class B { public C Prop2 => null; } class C { public object Prop3 => null; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... p3: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... op3: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, DiagnosticDescription.None, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_IOperation_FieldsInStructs() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Field1.Field2.Field3: null, Field4: null }; }/*</bind>*/ } struct A { public B? Field1; public B? Field4; } struct B { public C? Field2; } struct C { public object Field3; } "; var expectedDiagnostics = new[] { // (9,22): warning CS0649: Field 'A.Field1' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("A.Field1", "").WithLocation(9, 22), // (9,40): warning CS0649: Field 'A.Field4' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("A.Field4", "").WithLocation(9, 40), // (10,22): warning CS0649: Field 'B.Field2' is never assigned to, and will always have its default value // struct B { public C? Field2; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("B.Field2", "").WithLocation(10, 22), // (11,26): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // struct C { public object Field3; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(11, 26) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(expectedDiagnostics); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... d4: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... ld4: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_Explainer() { var src = @" class Program { void M(A a) { _ = a switch // 1 { { BProp.BoolProp: true } => 1 }; _ = a switch // 2 { { BProp.IntProp: <= 0 } => 1 }; } } class A { public B BProp => null; } class B { public bool BoolProp => true; public int IntProp => 0; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { BoolProp: false } }' is not covered. // _ = a switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { BoolProp: false } }").WithLocation(6, 15), // (11,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { IntProp: 1 } }' is not covered. // _ = a switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { IntProp: 1 } }").WithLocation(11, 15) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_BadMemberAccess() { var program = @" class C { C Field1, Field2, Field3; public static void Main() { _ = new C() is { Field1?.Field2: {} }; // 1 _ = new C() is { Field1!.Field2: {} }; // 2 _ = new C() is { Missing: null }; // 3 _ = new C() is { Field3.Missing: {} }; // 4 _ = new C() is { Missing1.Missing2: {} }; // 5 } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0169: The field 'C.Field1' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("C.Field1").WithLocation(4, 7), // (4,15): warning CS0169: The field 'C.Field2' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field2").WithArguments("C.Field2").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1?.Field2: {} }; // 1 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1?.Field2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1!.Field2: {} }; // 2 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1!").WithLocation(8, 26), // (9,26): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Missing: null }; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(9, 26), // (10,33): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Field3.Missing: {} }; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(10, 33), // (11,26): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = new C() is { Missing1.Missing2: {} }; // 5 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(11, 26) ); } [Fact] public void ExtendedPropertyPatterns_IOperationOnMissing() { var program = @" class C { public void M() { _ = this is { Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing' // _ = this is { Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Missing: null') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnNestedMissing() { var program = @" class C { int Property { get; set; } public void M() { _ = this is { Property.Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (7,32): error CS0117: 'int' does not contain a definition for 'Missing' // _ = this is { Property.Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("int", "Missing").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { P ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Property. ... ing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Property') Member: IPropertyReferenceOperation: System.Int32 C.Property { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Property') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Property') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Property') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: null, MatchedType: System.Int32, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Property.Missing') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Property.Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnTwoMissing() { var program = @" class C { public void M() { _ = this is { Missing1.Missing2: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = this is { Missing1.Missing2: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ng2: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing1. ... ng2: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1.Missing2') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1.Missing2') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_SuppressionOnPattern() { var program = @" #nullable enable public class ContainerType { public class Type { public void M() { const Type c = null!; if (this is c!) {} if (this is (c!)) {} if (this is Type!) {} // 1 if (this is ContainerType!.Type) {} // 2 if (this is ContainerType.Type!) {} // 3 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (12,25): error CS8598: The suppression operator is not allowed in this context // if (this is Type!) {} // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "Type!").WithLocation(12, 25), // (13,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType!.Type) {} // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType").WithLocation(13, 25), // (14,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType.Type!) {} // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType.Type!").WithLocation(14, 25) ); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_PointerAccessInPattern() { var program = @" public class Type { public unsafe void M(S* s) { if (0 is s->X) {} } } public struct S { public int X; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.UnsafeDebugDll); compilation.VerifyEmitDiagnostics( // (6,18): error CS0150: A constant value is expected // if (0 is s->X) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "s->X").WithLocation(6, 18) ); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_01() { var source = @" using System; class Program { public static void Main() { P p = new P(); Console.WriteLine(p is { X.Y: {}, Y.X: {} }); } } class P { public P X { get; } public P Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (14,14): warning CS0649: Field 'P.Y' is never assigned to, and will always have its default value null // public P Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("P.Y", "null").WithLocation(14, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("P P.Y", xySymbol.Symbol.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("P P.Y", yNameSymbol.Symbol.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("P P.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("P P.Y", ySymbol.Symbol.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_02() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } interface I1 { P X { get; } P Y { get; } } interface I2 { P X { get; } P Y { get; } } interface P : I1, I2 { // X and Y inherited ambiguously } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0229: Ambiguity between 'I1.X' and 'I2.X' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "X").WithArguments("I1.X", "I2.X").WithLocation(8, 34), // (8,43): error CS0229: Ambiguity between 'I1.Y' and 'I2.Y' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "Y").WithArguments("I1.Y", "I2.Y").WithLocation(8, 43) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.Ambiguous, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Equal(2, xSymbol.CandidateSymbols.Length); Assert.Equal("P I1.X { get; }", xSymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.X { get; }", xSymbol.CandidateSymbols[1].ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.Ambiguous, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Equal(2, ySymbol.CandidateSymbols.Length); Assert.Equal("P I1.Y { get; }", ySymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.Y { get; }", ySymbol.CandidateSymbols[1].ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_03() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } class P { } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0117: 'P' does not contain a definition for 'X' // Console.WriteLine(p is { X: 3, Y: 4 }); Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("P", "X").WithLocation(8, 34) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = subpatterns[0].ExpressionColon.Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Empty(xSymbol.CandidateSymbols); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = subpatterns[1].ExpressionColon.Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Empty(ySymbol.CandidateSymbols); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_04() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(new C() is { X.Y: {} }); Console.WriteLine(new S() is { Y.X: {} }); } } class C { public S? X { get; } } struct S { public C Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (17,14): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value null // public C Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "null").WithLocation(17, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("C S.Y", xySymbol.Symbol.ToTestDisplayString()); var xyType = model.GetTypeInfo(xy); Assert.Equal("C", xyType.Type.ToTestDisplayString()); Assert.Equal("C", xyType.ConvertedType.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var xType = model.GetTypeInfo(x); Assert.Equal("S?", xType.Type.ToTestDisplayString()); Assert.Equal("S?", xType.ConvertedType.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("C S.Y", yNameSymbol.Symbol.ToTestDisplayString()); var yNameType = model.GetTypeInfo(yName); Assert.Equal("C", yNameType.Type.ToTestDisplayString()); Assert.Equal("C", yNameType.ConvertedType.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var yxType = model.GetTypeInfo(yx); Assert.Equal("S?", yxType.Type.ToTestDisplayString()); Assert.Equal("S?", yxType.ConvertedType.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("C S.Y", ySymbol.Symbol.ToTestDisplayString()); var yType = model.GetTypeInfo(y); Assert.Equal("C", yType.Type.ToTestDisplayString()); Assert.Equal("C", yType.ConvertedType.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); var xNameType = model.GetTypeInfo(xName); Assert.Equal("S?", xNameType.Type.ToTestDisplayString()); Assert.Equal("S?", xNameType.ConvertedType.ToTestDisplayString()); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("Program.Main", @" { // Code size 92 (0x5c) .maxstack 2 .locals init (C V_0, S? V_1, S V_2) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_002b IL_000a: ldloc.0 IL_000b: callvirt ""S? C.X.get"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: call ""bool S?.HasValue.get"" IL_0018: brfalse.s IL_002b IL_001a: ldloca.s V_1 IL_001c: call ""S S?.GetValueOrDefault()"" IL_0021: ldfld ""C S.Y"" IL_0026: ldnull IL_0027: cgt.un IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: call ""void System.Console.WriteLine(bool)"" IL_0031: nop IL_0032: ldloca.s V_2 IL_0034: initobj ""S"" IL_003a: ldloc.2 IL_003b: ldfld ""C S.Y"" IL_0040: stloc.0 IL_0041: ldloc.0 IL_0042: brfalse.s IL_0054 IL_0044: ldloc.0 IL_0045: callvirt ""S? C.X.get"" IL_004a: stloc.1 IL_004b: ldloca.s V_1 IL_004d: call ""bool S?.HasValue.get"" IL_0052: br.s IL_0055 IL_0054: ldc.i4.0 IL_0055: call ""void System.Console.WriteLine(bool)"" IL_005a: nop IL_005b: ret } "); } [Fact] public void ExtendedPropertyPatterns_Nullability_Properties() { var program = @" #nullable enable class C { C? Prop { get; } public void M() { if (this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 1 } if (this is { Prop.Prop: {} }) { this.Prop.ToString(); this.Prop.Prop.ToString(); } if (this is { Prop: null } && this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 2 } if (this is { Prop: null } || this is { Prop.Prop: null }) { this.Prop.ToString(); // 3 this.Prop.Prop.ToString(); // 4 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(9, 13), // (20,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(20, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(26, 13)); } [Fact] public void ExtendedPropertyPatterns_Nullability_AnnotatedFields() { var program = @" #nullable enable class C { public void M(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); // 4 } } } class C1 { public C2? Prop1 = null; } class C2 { public object? Prop2 = null; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(8, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(25, 13) ); } [Fact] public void ExtendedPropertyPatterns_Nullability_UnannotatedFields() { var program = @" #nullable enable class C { public void M1(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M2(C1 c1) { if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M3(C1 c1) { if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } else { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); } } public void M4(C1 c1) { if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 4 c1.Prop1.Prop2.ToString(); // 5 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } } class C1 { public C2 Prop1 = null!; } class C2 { public object Prop2 = null!; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(34, 13), // (38,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(38, 13), // (48,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(48, 13), // (49,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(49, 13) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInPositionalPattern() { var source = @" class C { C Property { get; set; } void M() { _ = this is (Property.Property: null, Property: null); } public void Deconstruct(out C c1, out C c2) => throw null; } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyEmitDiagnostics( // (8,22): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property.Property").WithArguments("extended property patterns", "10.0").WithLocation(8, 22), // (8,22): error CS1001: Identifier expected // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Property.Property").WithLocation(8, 22), // (8,47): error CS8517: The name 'Property' does not match the corresponding 'Deconstruct' parameter 'c2'. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "Property").WithArguments("Property", "c2").WithLocation(8, 47) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInITuplePattern() { var source = @" class C { void M() { System.Runtime.CompilerServices.ITuple t = null; var r = t is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,23): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(7, 23), // (7,31): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(7, 31) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInValueTuplePattern() { var source = @" class C { void M() { _ = (1, 2) is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (6,24): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(6, 24), // (6,32): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(6, 32) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { [ObsoleteAttribute(""error Prop1"", true)] public C2 Prop1 { get; set; } } class C2 { [ObsoleteAttribute(""error Prop2"", true)] public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1").WithArguments("C1.Prop1", "error Prop1").WithLocation(7, 21), // (7,27): error CS0619: 'C2.Prop2' is obsolete: 'error Prop2' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop2").WithArguments("C2.Prop2", "error Prop2").WithLocation(7, 27) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteAccessor() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { [ObsoleteAttribute(""error Prop1"", true)] get; set; } } class C2 { public object Prop2 { get; [ObsoleteAttribute(""error Prop2"", true)] set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1.get' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1.Prop2").WithArguments("C1.Prop1.get", "error Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_InaccessibleProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { private C2 Prop1 { get; set; } } class C2 { private object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0122: 'C1.Prop1' is inaccessible due to its protection level // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_BadAccess, "Prop1").WithArguments("C1.Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionTree() { var program = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { public void M1(C1 c1) { Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { get; set; } } class C2 { public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,48): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "c1 is { Prop1.Prop2: null }").WithLocation(9, 48) ); } [Fact] public void ExtendedPropertyPatterns_EvaluationOrder() { var program = @" if (new C() is { Prop1.True: true, Prop1.Prop2: not null }) { System.Console.WriteLine(""matched1""); } if (new C() is { Prop1.Prop2: not null, Prop1.True: true }) { System.Console.WriteLine(""matched2""); } if (new C() is { Prop1.Prop2: not null, Prop2.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1.Prop2.Prop3.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1: { Prop2.Prop3.True: true } }) { System.Console.WriteLine(""matched4""); } if (new C() is { Prop1.True: false, Prop1.Prop2: not null }) { throw null; } class C { public C Prop1 { get { System.Console.Write(""Prop1 ""); return this; } } public C Prop2 { get { System.Console.Write(""Prop2 ""); return this; } } public C Prop3 { get { System.Console.Write(""Prop3 ""); return this; } } public bool True { get { System.Console.Write(""True ""); return true; } } } "; CompileAndVerify(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, expectedOutput: @" Prop1 True Prop2 matched1 Prop1 Prop2 True matched2 Prop1 Prop2 Prop2 True matched3 Prop1 Prop2 Prop3 True matched3 Prop1 Prop2 Prop3 True matched4 Prop1 True"); } [Fact] public void ExtendedPropertyPatterns_StaticMembers() { var program = @" _ = new C() is { Static: null }; // 1 _ = new C() is { Instance.Static: null }; // 2 _ = new C() is { Static.Instance: null }; // 3 class C { public C Instance { get; set; } public static C Static { get; set; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static: null }; // 1 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(2, 18), // (3,27): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Instance.Static: null }; // 2 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(3, 27), // (4,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static.Instance: null }; // 3 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(4, 18) ); } [Fact] public void ExtendedPropertyPatterns_Exhaustiveness() { var program = @" _ = new C() switch // 1 { { Prop.True: true } => 0 }; _ = new C() switch { { Prop.True: true } => 0, { Prop.True: false } => 0 }; #nullable enable _ = new C() switch // 2 { { Prop.Prop: null } => 0 }; class C { public C Prop { get => throw null!; } public bool True { get => throw null!; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { True: false } }' is not covered. // _ = new C() switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { True: false } }").WithLocation(2, 13), // (14,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { Prop: not null } }' is not covered. // _ = new C() switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { Prop: not null } }").WithLocation(14, 13) ); } [Fact, WorkItem(55184, "https://github.com/dotnet/roslyn/issues/55184")] public void Repro55184() { var source = @" var x = """"; _ = x is { Error: { Length: > 0 } }; _ = x is { Error.Length: > 0 }; _ = x is { Length: { Error: > 0 } }; _ = x is { Length.Error: > 0 }; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error: { Length: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(4, 12), // (5,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error.Length: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(5, 12), // (6,22): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length: { Error: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(6, 22), // (7,19): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length.Error: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(7, 19) ); } public class FlowAnalysisTests : FlowTestBase { [Fact] public void RegionInIsPattern01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(object o) { _ = o switch { string { Length: 0 } s => /*<bind>*/s.ToString()/*</bind>*/, _ = throw null }; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("o, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.UnsafeAddressTaken)); } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/XmlLiteralTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Tools/ExternalAccess/OmniSharp.CSharp/Completion/OmniSharpCompletionProviderNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Completion.Providers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.Completion { internal static class OmniSharpCompletionProviderNames { internal static string ObjectCreationCompletionProvider = typeof(ObjectCreationCompletionProvider).FullName; internal static string OverrideCompletionProvider = typeof(OverrideCompletionProvider).FullName; internal static string PartialMethodCompletionProvider = typeof(PartialMethodCompletionProvider).FullName; internal static string InternalsVisibleToCompletionProvider = typeof(InternalsVisibleToCompletionProvider).FullName; internal static string TypeImportCompletionProvider = typeof(TypeImportCompletionProvider).FullName; internal static string ExtensionMethodImportCompletionProvider = typeof(ExtensionMethodImportCompletionProvider).FullName; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Completion.Providers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.Completion { internal static class OmniSharpCompletionProviderNames { internal static string ObjectCreationCompletionProvider = typeof(ObjectCreationCompletionProvider).FullName; internal static string OverrideCompletionProvider = typeof(OverrideCompletionProvider).FullName; internal static string PartialMethodCompletionProvider = typeof(PartialMethodCompletionProvider).FullName; internal static string InternalsVisibleToCompletionProvider = typeof(InternalsVisibleToCompletionProvider).FullName; internal static string TypeImportCompletionProvider = typeof(TypeImportCompletionProvider).FullName; internal static string ExtensionMethodImportCompletionProvider = typeof(ExtensionMethodImportCompletionProvider).FullName; } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/LogLevel.cs
// Licensed to the .NET Foundation under one or more 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.Internal.Log { /// <summary> /// Defines logging severity levels. Each logger may choose to report differently based on the level of the message being logged. /// /// Copied from Microsoft.Extensions.Logging https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel /// /// </summary> internal enum LogLevel { /// <summary> /// Logs that contain the most detailed messages. These messages may contain sensitive application data. These messages are disabled by default and should never be enabled in a production environment. /// </summary> Trace = 0, /// <summary> /// Logs that are used for interactive investigation during development. These logs should primarily contain information useful for debugging and have no long-term value. /// </summary> Debug = 1, /// <summary> /// Logs that track the general flow of the application. These logs should have long-term value. /// </summary> Information = 2, /// <summary> /// Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the application execution to stop. /// </summary> Warning = 3, /// <summary> /// Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a failure in the current activity, not an application-wide failure. /// </summary> Error = 4, /// <summary> /// Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires immediate attention. /// </summary> Critical = 5, /// <summary> /// Not used for writing log messages. Specifies that a logging category should not write any messages. /// </summary> None = 6 } }
// Licensed to the .NET Foundation under one or more 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.Internal.Log { /// <summary> /// Defines logging severity levels. Each logger may choose to report differently based on the level of the message being logged. /// /// Copied from Microsoft.Extensions.Logging https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel /// /// </summary> internal enum LogLevel { /// <summary> /// Logs that contain the most detailed messages. These messages may contain sensitive application data. These messages are disabled by default and should never be enabled in a production environment. /// </summary> Trace = 0, /// <summary> /// Logs that are used for interactive investigation during development. These logs should primarily contain information useful for debugging and have no long-term value. /// </summary> Debug = 1, /// <summary> /// Logs that track the general flow of the application. These logs should have long-term value. /// </summary> Information = 2, /// <summary> /// Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the application execution to stop. /// </summary> Warning = 3, /// <summary> /// Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a failure in the current activity, not an application-wide failure. /// </summary> Error = 4, /// <summary> /// Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires immediate attention. /// </summary> Critical = 5, /// <summary> /// Not used for writing log messages. Specifies that a logging category should not write any messages. /// </summary> None = 6 } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Server/VBCSCompiler/ICompilerServerHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface ICompilerServerHost { ICompilerServerLogger Logger { get; } BuildResponse RunCompilation(in RunRequest request, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface ICompilerServerHost { ICompilerServerLogger Logger { get; } BuildResponse RunCompilation(in RunRequest request, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.SemanticModelReuse { [UseExportProvider] public class SemanticModelReuseTests { private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net40.mscorlib) .AddDocument("Document", SourceText.From(code)); } #region C# tests [Fact] public async Task NullBodyReturnsNormalSemanticModel1_CSharp() { var document = CreateDocument("", LanguageNames.CSharp); // trying to get a model for null should return a non-speculative model var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model.IsSpeculativeSemanticModel); } [Fact] public async Task NullBodyReturnsNormalSemanticModel2_CSharp() { var source = "class C { void M() { return; } }"; var document = CreateDocument(source, LanguageNames.CSharp); // Even if we've primed things with a real location, getting a semantic model for null should return a // non-speculative model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); } [Fact] public async Task SameSyntaxTreeReturnsNonSpeculativeModel_CSharp() { var source = "class C { void M() { return; } }"; var document = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. The next call will also use the // same syntax tree, so it should get the same semantic model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); // Should be the same models. Assert.Equal(model1, model2); // Which also should be the normal model the document provides. var actualModel = await document.GetSemanticModelAsync(); Assert.Equal(model1, actualModel); } [Fact] public async Task InBodyEditShouldProduceCachedModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { void M() { return null; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); } [Fact] public async Task OutOfBodyEditShouldProduceFreshModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { long M() { return; } }")); // We changed the return type, so we can't reuse the previous model. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model2.IsSpeculativeSemanticModel); var document3 = document2.WithText(SourceText.From("class C { long M() { return 0; } }")); // We are now again only editing a method body so we should be able to get a speculative model. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { void M() { return 0; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { void M() { return 1; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_CSharp() { var source = "class C { int M { get { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { int M { get { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { int M { get { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_CSharp() { var source = "class C { event System.Action E { add { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Indexer_CSharp() { var source = "class C { int this[int i] { get { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } #endregion #region Visual Basic tests [Fact] public async Task NullBodyReturnsNormalSemanticModel1_VisualBasic() { var document = CreateDocument("", LanguageNames.VisualBasic); // trying to get a model for null should return a non-speculative model var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model.IsSpeculativeSemanticModel); } [Fact] public async Task NullBodyReturnsNormalSemanticModel2_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document = CreateDocument(source, LanguageNames.VisualBasic); // Even if we've primed things with a real location, getting a semantic model for null should return a // non-speculative model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); } [Fact] public async Task SameSyntaxTreeReturnsNonSpeculativeModel_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. The next call will also use the // same syntax tree, so it should get the same semantic model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); // Should be the same models. Assert.Equal(model1, model2); // Which also should be the normal model the document provides. var actualModel = await document.GetSemanticModelAsync(); Assert.Equal(model1, actualModel); } [Fact] public async Task InBodyEditShouldProduceCachedModel_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C sub M() return nothing end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); } [Fact] public async Task OutOfBodyEditShouldProduceFreshModel_VisualBasic() { var source1 = @" class C sub M() return end sub end class"; var document1 = CreateDocument(source1, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source1.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var source2 = @" class C function M() as long return end function end class"; var document2 = document1.WithText(SourceText.From(source2)); // We changed the return type, so we can't reuse the previous model. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); Assert.False(model2.IsSpeculativeSemanticModel); var document3 = document2.WithText(SourceText.From(@" class C function M() as long return 0 end function end class")); // We are now again only editing a method body so we should be able to get a speculative model. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_VisualBasic() { var source = @"class C sub M() return end sub end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C sub M() return 0 end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C sub M() return 1 end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_VisualBasic() { var source = @" class C readonly property M as integer get return 0 end get end property end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C readonly property M as integer get return 1 end get end property end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C readonly property M as integer get return 2 end get end property end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_VisualBasic() { var source = @" class C public custom event E as System.Action addhandler(value as System.Action) return 0 end addhandler end event end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C public custom event E as System.Action addhandler(value as System.Action) return 1 end addhandler end event end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C public custom event E as System.Action addhandler(value as System.Action) return 2 end addhandler end event end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } #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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.SemanticModelReuse { [UseExportProvider] public class SemanticModelReuseTests { private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net40.mscorlib) .AddDocument("Document", SourceText.From(code)); } #region C# tests [Fact] public async Task NullBodyReturnsNormalSemanticModel1_CSharp() { var document = CreateDocument("", LanguageNames.CSharp); // trying to get a model for null should return a non-speculative model var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model.IsSpeculativeSemanticModel); } [Fact] public async Task NullBodyReturnsNormalSemanticModel2_CSharp() { var source = "class C { void M() { return; } }"; var document = CreateDocument(source, LanguageNames.CSharp); // Even if we've primed things with a real location, getting a semantic model for null should return a // non-speculative model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); } [Fact] public async Task SameSyntaxTreeReturnsNonSpeculativeModel_CSharp() { var source = "class C { void M() { return; } }"; var document = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. The next call will also use the // same syntax tree, so it should get the same semantic model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); // Should be the same models. Assert.Equal(model1, model2); // Which also should be the normal model the document provides. var actualModel = await document.GetSemanticModelAsync(); Assert.Equal(model1, actualModel); } [Fact] public async Task InBodyEditShouldProduceCachedModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { void M() { return null; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); } [Fact] public async Task OutOfBodyEditShouldProduceFreshModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { long M() { return; } }")); // We changed the return type, so we can't reuse the previous model. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model2.IsSpeculativeSemanticModel); var document3 = document2.WithText(SourceText.From("class C { long M() { return 0; } }")); // We are now again only editing a method body so we should be able to get a speculative model. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_CSharp() { var source = "class C { void M() { return; } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { void M() { return 0; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { void M() { return 1; } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_CSharp() { var source = "class C { int M { get { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { int M { get { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { int M { get { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_CSharp() { var source = "class C { event System.Action E { add { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Indexer_CSharp() { var source = "class C { int this[int i] { get { return 0; } } }"; var document1 = CreateDocument(source, LanguageNames.CSharp); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 1; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 2; } } }")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } #endregion #region Visual Basic tests [Fact] public async Task NullBodyReturnsNormalSemanticModel1_VisualBasic() { var document = CreateDocument("", LanguageNames.VisualBasic); // trying to get a model for null should return a non-speculative model var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model.IsSpeculativeSemanticModel); } [Fact] public async Task NullBodyReturnsNormalSemanticModel2_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document = CreateDocument(source, LanguageNames.VisualBasic); // Even if we've primed things with a real location, getting a semantic model for null should return a // non-speculative model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); } [Fact] public async Task SameSyntaxTreeReturnsNonSpeculativeModel_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. The next call will also use the // same syntax tree, so it should get the same semantic model. var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); Assert.False(model2.IsSpeculativeSemanticModel); // Should be the same models. Assert.Equal(model1, model2); // Which also should be the normal model the document provides. var actualModel = await document.GetSemanticModelAsync(); Assert.Equal(model1, actualModel); } [Fact] public async Task InBodyEditShouldProduceCachedModel_VisualBasic() { var source = @" class C sub M() return end sub end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C sub M() return nothing end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); } [Fact] public async Task OutOfBodyEditShouldProduceFreshModel_VisualBasic() { var source1 = @" class C sub M() return end sub end class"; var document1 = CreateDocument(source1, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source1.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var source2 = @" class C function M() as long return end function end class"; var document2 = document1.WithText(SourceText.From(source2)); // We changed the return type, so we can't reuse the previous model. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); Assert.False(model2.IsSpeculativeSemanticModel); var document3 = document2.WithText(SourceText.From(@" class C function M() as long return 0 end function end class")); // We are now again only editing a method body so we should be able to get a speculative model. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_VisualBasic() { var source = @"class C sub M() return end sub end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C sub M() return 0 end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C sub M() return 1 end sub end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_VisualBasic() { var source = @" class C readonly property M as integer get return 0 end get end property end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C readonly property M as integer get return 1 end get end property end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C readonly property M as integer get return 2 end get end property end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } [Fact] public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_VisualBasic() { var source = @" class C public custom event E as System.Action addhandler(value as System.Action) return 0 end addhandler end event end class"; var document1 = CreateDocument(source, LanguageNames.VisualBasic); // First call will prime the cache to point at the real semantic model. var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.False(model1.IsSpeculativeSemanticModel); var document2 = document1.WithText(SourceText.From(@" class C public custom event E as System.Action addhandler(value as System.Action) return 1 end addhandler end event end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model2.IsSpeculativeSemanticModel); var document3 = document1.WithText(SourceText.From(@" class C public custom event E as System.Action addhandler(value as System.Action) return 2 end addhandler end event end class")); // This should be able to get a speculative model using the original model we primed the cache with. var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None); Assert.True(model3.IsSpeculativeSemanticModel); } #endregion } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.AliasAmbiguousType { internal abstract class AbstractAliasAmbiguousTypeCodeFixProvider : CodeFixProvider { protected abstract string GetTextPreviewOfChange(string aliasName, ITypeSymbol typeSymbol); public override FixAllProvider? GetFixAllProvider() => null; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Innermost: We are looking for an IdentifierName. IdentifierName is sometimes at the same span as its parent (e.g. SimpleBaseTypeSyntax). var diagnosticNode = root.FindNode(context.Span, getInnermostNodeForTie: true); if (!syntaxFacts.IsIdentifierName(diagnosticNode)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = semanticModel.GetSymbolInfo(diagnosticNode, cancellationToken); if (SymbolCandidatesContainsSupportedSymbols(symbolInfo)) { var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var syntaxGenerator = document.GetRequiredLanguageService<SyntaxGenerator>(); var compilation = semanticModel.Compilation; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var codeActionsBuilder = ImmutableArray.CreateBuilder<CodeAction>(symbolInfo.CandidateSymbols.Length); foreach (var symbol in symbolInfo.CandidateSymbols.Cast<ITypeSymbol>()) { var typeName = symbol.Name; var codeActionPreviewText = GetTextPreviewOfChange(typeName, symbol); codeActionsBuilder.Add(new MyCodeAction(codeActionPreviewText, c => { var aliasDirective = syntaxGenerator.AliasImportDeclaration(typeName, symbol); var newRoot = addImportService.AddImport(compilation, root, diagnosticNode, aliasDirective, syntaxGenerator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); return Task.FromResult(document.WithSyntaxRoot(newRoot)); })); } var groupingTitle = string.Format(FeaturesResources.Alias_ambiguous_type_0, diagnosticNode.ToString()); var groupingCodeAction = new CodeActionWithNestedActions(groupingTitle, codeActionsBuilder.ToImmutable(), isInlinable: true); context.RegisterCodeFix(groupingCodeAction, context.Diagnostics.First()); } } private static bool SymbolCandidatesContainsSupportedSymbols(SymbolInfo symbolInfo) => symbolInfo.CandidateReason == CandidateReason.Ambiguous && // Arity: Aliases can only name closed constructed types. (See also proposal https://github.com/dotnet/csharplang/issues/1239) // Aliasing as a closed constructed type is possible but would require to remove the type arguments from the diagnosed node. // It is unlikely that the user wants that and so generic types are not supported. symbolInfo.CandidateSymbols.All(symbol => symbol.IsKind(SymbolKind.NamedType) && symbol.GetArity() == 0); private class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, equivalenceKey: 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.AliasAmbiguousType { internal abstract class AbstractAliasAmbiguousTypeCodeFixProvider : CodeFixProvider { protected abstract string GetTextPreviewOfChange(string aliasName, ITypeSymbol typeSymbol); public override FixAllProvider? GetFixAllProvider() => null; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Innermost: We are looking for an IdentifierName. IdentifierName is sometimes at the same span as its parent (e.g. SimpleBaseTypeSyntax). var diagnosticNode = root.FindNode(context.Span, getInnermostNodeForTie: true); if (!syntaxFacts.IsIdentifierName(diagnosticNode)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = semanticModel.GetSymbolInfo(diagnosticNode, cancellationToken); if (SymbolCandidatesContainsSupportedSymbols(symbolInfo)) { var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var syntaxGenerator = document.GetRequiredLanguageService<SyntaxGenerator>(); var compilation = semanticModel.Compilation; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var codeActionsBuilder = ImmutableArray.CreateBuilder<CodeAction>(symbolInfo.CandidateSymbols.Length); foreach (var symbol in symbolInfo.CandidateSymbols.Cast<ITypeSymbol>()) { var typeName = symbol.Name; var codeActionPreviewText = GetTextPreviewOfChange(typeName, symbol); codeActionsBuilder.Add(new MyCodeAction(codeActionPreviewText, c => { var aliasDirective = syntaxGenerator.AliasImportDeclaration(typeName, symbol); var newRoot = addImportService.AddImport(compilation, root, diagnosticNode, aliasDirective, syntaxGenerator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); return Task.FromResult(document.WithSyntaxRoot(newRoot)); })); } var groupingTitle = string.Format(FeaturesResources.Alias_ambiguous_type_0, diagnosticNode.ToString()); var groupingCodeAction = new CodeActionWithNestedActions(groupingTitle, codeActionsBuilder.ToImmutable(), isInlinable: true); context.RegisterCodeFix(groupingCodeAction, context.Diagnostics.First()); } } private static bool SymbolCandidatesContainsSupportedSymbols(SymbolInfo symbolInfo) => symbolInfo.CandidateReason == CandidateReason.Ambiguous && // Arity: Aliases can only name closed constructed types. (See also proposal https://github.com/dotnet/csharplang/issues/1239) // Aliasing as a closed constructed type is possible but would require to remove the type arguments from the diagnosed node. // It is unlikely that the user wants that and so generic types are not supported. symbolInfo.CandidateSymbols.All(symbol => symbol.IsKind(SymbolKind.NamedType) && symbol.GetArity() == 0); private class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, equivalenceKey: title) { } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.ControlFlowAnalysis.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.ExtractMethod Partial Public Class ExtractMethodTests ''' <summary> ''' This contains tests for Extract Method components that depend on Control Flow Analysis API ''' (A) Selection Validator ''' (B) Analyzer ''' </summary> ''' <remarks></remarks> <[UseExportProvider]> Public Class FlowAnalysis <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitSub() As Threading.Tasks.Task Dim code = <text>Class Test Sub Test() [|Exit Sub|] End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitFunction() As Threading.Tasks.Task Dim code = <text>Class Test Function Test1() As Integer Console.Write(42) [|Test1 = 1 Console.Write(5) Exit Function|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540046")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestReturnStatement() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) [|Return x|] End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Return NewMethod(x) End Function Private Shared Function NewMethod(x As Integer) As Integer Return x End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranch() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchInvalidSelection() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i)|] i = i + 1 Loop Until i > 5 Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchWithContinue() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionLeftOfAssignment() As Task Dim code = <text>Class A Protected x As Integer = 1 Public Sub New() [|x|] = 42 End Sub End Class</text> Dim expected = <text>Class A Protected x As Integer = 1 Public Sub New() NewMethod() End Sub Private Sub NewMethod() x = 42 End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionOfArrayLiterals() As Task Dim code = <text>Class A Public Sub Test() Dim numbers = New Integer() [|{1,2,3,4}|] End Sub End Class</text> Dim expected = <text>Class A Public Sub Test() Dim numbers = GetNumbers() End Sub Private Shared Function GetNumbers() As Integer() Return New Integer() {1, 2, 3, 4} End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If Console.WriteLine(1)|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test(b As Boolean) NewMethod(b) End Sub Private Shared Sub NewMethod(b As Boolean) If b Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_1() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If|] Console.WriteLine(1) End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_2() As Threading.Tasks.Task Dim code = <text>Imports System Class A Function Test(b As Boolean) as Integer [|If b Then Return 1 End If Console.WriteLine(1)|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_3() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() End Sub Private Shared Sub NewMethod() Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_4() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub|] Console.WriteLine(1) End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() Console.WriteLine(1) End Sub Private Shared Sub NewMethod() Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_5() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1)|] End Sub End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() Dim d As Action = Sub() NewMethod() End Sub End Sub Private Shared Sub NewMethod() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154"), WorkItem(541484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541484")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_6() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If|] Console.WriteLine(1) End Function End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(543670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543670")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function AnonymousLambdaInVarDecl() As Task Dim code = <text>Imports System Module Program Sub Main [|Dim u = Function(x As Integer) 5|] u.Invoke(Nothing) End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(531451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531451"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_01() As Task Dim code = <text>Module Program Sub Main(args As String()) [|If True Then ElseIf True Then Return|] End Sub End Module</text> Dim expected = <text>Module Program Sub Main(args As String()) NewMethod() End Sub Private Sub NewMethod() If True Then ElseIf True Then Return End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(547156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547156"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_02() As Task Dim code = <text>Module Program Sub Main() If True Then Dim x [|Else Console.WriteLine()|] End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(530625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530625"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestUnreachableEndInFunction() As Task Dim code = <text>Module Program Function Goo() As Integer If True Then [|Do : Loop|] ' Extract method Exit Function Else Return 0 End If End Function End Module</text> Dim expected = <text>Module Program Function Goo() As Integer If True Then NewMethod() ' Extract method Exit Function Else Return 0 End If End Function Private Sub NewMethod() Do : Loop End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(578066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578066"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitAsSupportedExitPoints() As Task Dim code = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) [|Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L|] End Function End Module</text> Dim expected = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) Return Await NewMethod(x) End Function Private Async Function NewMethod(x As Integer) As Task(Of Integer) Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L End Function End Module</text> Await TestExtractMethodAsync(code, expected) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod Partial Public Class ExtractMethodTests ''' <summary> ''' This contains tests for Extract Method components that depend on Control Flow Analysis API ''' (A) Selection Validator ''' (B) Analyzer ''' </summary> ''' <remarks></remarks> <[UseExportProvider]> Public Class FlowAnalysis <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitSub() As Threading.Tasks.Task Dim code = <text>Class Test Sub Test() [|Exit Sub|] End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitFunction() As Threading.Tasks.Task Dim code = <text>Class Test Function Test1() As Integer Console.Write(42) [|Test1 = 1 Console.Write(5) Exit Function|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540046")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestReturnStatement() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) [|Return x|] End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Return NewMethod(x) End Function Private Shared Function NewMethod(x As Integer) As Integer Return x End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranch() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchInvalidSelection() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i)|] i = i + 1 Loop Until i > 5 Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchWithContinue() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionLeftOfAssignment() As Task Dim code = <text>Class A Protected x As Integer = 1 Public Sub New() [|x|] = 42 End Sub End Class</text> Dim expected = <text>Class A Protected x As Integer = 1 Public Sub New() NewMethod() End Sub Private Sub NewMethod() x = 42 End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionOfArrayLiterals() As Task Dim code = <text>Class A Public Sub Test() Dim numbers = New Integer() [|{1,2,3,4}|] End Sub End Class</text> Dim expected = <text>Class A Public Sub Test() Dim numbers = GetNumbers() End Sub Private Shared Function GetNumbers() As Integer() Return New Integer() {1, 2, 3, 4} End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If Console.WriteLine(1)|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test(b As Boolean) NewMethod(b) End Sub Private Shared Sub NewMethod(b As Boolean) If b Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_1() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If|] Console.WriteLine(1) End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_2() As Threading.Tasks.Task Dim code = <text>Imports System Class A Function Test(b As Boolean) as Integer [|If b Then Return 1 End If Console.WriteLine(1)|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_3() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() End Sub Private Shared Sub NewMethod() Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_4() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub|] Console.WriteLine(1) End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() Console.WriteLine(1) End Sub Private Shared Sub NewMethod() Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_5() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1)|] End Sub End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() Dim d As Action = Sub() NewMethod() End Sub End Sub Private Shared Sub NewMethod() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154"), WorkItem(541484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541484")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_6() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If|] Console.WriteLine(1) End Function End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(543670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543670")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function AnonymousLambdaInVarDecl() As Task Dim code = <text>Imports System Module Program Sub Main [|Dim u = Function(x As Integer) 5|] u.Invoke(Nothing) End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(531451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531451"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_01() As Task Dim code = <text>Module Program Sub Main(args As String()) [|If True Then ElseIf True Then Return|] End Sub End Module</text> Dim expected = <text>Module Program Sub Main(args As String()) NewMethod() End Sub Private Sub NewMethod() If True Then ElseIf True Then Return End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(547156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547156"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_02() As Task Dim code = <text>Module Program Sub Main() If True Then Dim x [|Else Console.WriteLine()|] End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(530625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530625"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestUnreachableEndInFunction() As Task Dim code = <text>Module Program Function Goo() As Integer If True Then [|Do : Loop|] ' Extract method Exit Function Else Return 0 End If End Function End Module</text> Dim expected = <text>Module Program Function Goo() As Integer If True Then NewMethod() ' Extract method Exit Function Else Return 0 End If End Function Private Sub NewMethod() Do : Loop End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(578066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578066"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitAsSupportedExitPoints() As Task Dim code = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) [|Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L|] End Function End Module</text> Dim expected = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) Return Await NewMethod(x) End Function Private Async Function NewMethod(x As Integer) As Task(Of Integer) Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L End Function End Module</text> Await TestExtractMethodAsync(code, expected) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/VisualBasic/Portable/AddAnonymousTypeMemberName/VisualBasicAddAnonymousTypeMemberNameCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.AddAnonymousTypeMemberName Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddAnonymousTypeMemberName), [Shared]> Friend Class VisualBasicAddAnonymousTypeMemberNameCodeFixProvider Inherits AbstractAddAnonymousTypeMemberNameCodeFixProvider(Of ExpressionSyntax, ObjectMemberInitializerSyntax, FieldInitializerSyntax) Private Const BC36556 As String = NameOf(BC36556) ' Anonymous type member name can be inferred only from a simple or qualified name with no arguments. <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC36556) Protected Overrides Function HasName(declarator As FieldInitializerSyntax) As Boolean Return Not TypeOf declarator Is InferredFieldInitializerSyntax End Function Protected Overrides Function GetExpression(declarator As FieldInitializerSyntax) As ExpressionSyntax Return DirectCast(declarator, InferredFieldInitializerSyntax).Expression End Function Protected Overrides Function WithName(declarator As FieldInitializerSyntax, nameToken As SyntaxToken) As FieldInitializerSyntax Dim inferredField = DirectCast(declarator, InferredFieldInitializerSyntax) Return SyntaxFactory.NamedFieldInitializer( inferredField.KeyKeyword, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(nameToken), SyntaxFactory.Token(SyntaxKind.EqualsToken), inferredField.Expression).WithTriviaFrom(declarator) End Function Protected Overrides Function GetAnonymousObjectMemberNames(initializer As ObjectMemberInitializerSyntax) As IEnumerable(Of String) Return initializer.Initializers.OfType(Of NamedFieldInitializerSyntax). Select(Function(i) i.Name.Identifier.ValueText) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.AddAnonymousTypeMemberName Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddAnonymousTypeMemberName), [Shared]> Friend Class VisualBasicAddAnonymousTypeMemberNameCodeFixProvider Inherits AbstractAddAnonymousTypeMemberNameCodeFixProvider(Of ExpressionSyntax, ObjectMemberInitializerSyntax, FieldInitializerSyntax) Private Const BC36556 As String = NameOf(BC36556) ' Anonymous type member name can be inferred only from a simple or qualified name with no arguments. <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC36556) Protected Overrides Function HasName(declarator As FieldInitializerSyntax) As Boolean Return Not TypeOf declarator Is InferredFieldInitializerSyntax End Function Protected Overrides Function GetExpression(declarator As FieldInitializerSyntax) As ExpressionSyntax Return DirectCast(declarator, InferredFieldInitializerSyntax).Expression End Function Protected Overrides Function WithName(declarator As FieldInitializerSyntax, nameToken As SyntaxToken) As FieldInitializerSyntax Dim inferredField = DirectCast(declarator, InferredFieldInitializerSyntax) Return SyntaxFactory.NamedFieldInitializer( inferredField.KeyKeyword, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(nameToken), SyntaxFactory.Token(SyntaxKind.EqualsToken), inferredField.Expression).WithTriviaFrom(declarator) End Function Protected Overrides Function GetAnonymousObjectMemberNames(initializer As ObjectMemberInitializerSyntax) As IEnumerable(Of String) Return initializer.Initializers.OfType(Of NamedFieldInitializerSyntax). Select(Function(i) i.Name.Identifier.ValueText) End Function End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.DeclarationFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class MemberDeclarationSyntaxExtensions { private sealed class DeclarationFinder : CSharpSyntaxWalker { private readonly Dictionary<string, List<SyntaxToken>> _map = new(); private DeclarationFinder() : base(SyntaxWalkerDepth.Node) { } public static Dictionary<string, List<SyntaxToken>> GetAllDeclarations(SyntaxNode syntax) { var finder = new DeclarationFinder(); finder.Visit(syntax); return finder._map; } private void Add(SyntaxToken syntaxToken) { if (syntaxToken.Kind() == SyntaxKind.IdentifierToken) { var identifier = syntaxToken.ValueText; if (!_map.TryGetValue(identifier, out var list)) { list = new List<SyntaxToken>(); _map.Add(identifier, list); } list.Add(syntaxToken); } } public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { base.VisitVariableDeclarator(node); Add(node.Identifier); } public override void VisitCatchDeclaration(CatchDeclarationSyntax node) { base.VisitCatchDeclaration(node); Add(node.Identifier); } public override void VisitParameter(ParameterSyntax node) { base.VisitParameter(node); Add(node.Identifier); } public override void VisitFromClause(FromClauseSyntax node) { base.VisitFromClause(node); Add(node.Identifier); } public override void VisitLetClause(LetClauseSyntax node) { base.VisitLetClause(node); Add(node.Identifier); } public override void VisitJoinClause(JoinClauseSyntax node) { base.VisitJoinClause(node); Add(node.Identifier); } public override void VisitJoinIntoClause(JoinIntoClauseSyntax node) { base.VisitJoinIntoClause(node); Add(node.Identifier); } public override void VisitQueryContinuation(QueryContinuationSyntax node) { base.VisitQueryContinuation(node); Add(node.Identifier); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class MemberDeclarationSyntaxExtensions { private sealed class DeclarationFinder : CSharpSyntaxWalker { private readonly Dictionary<string, List<SyntaxToken>> _map = new(); private DeclarationFinder() : base(SyntaxWalkerDepth.Node) { } public static Dictionary<string, List<SyntaxToken>> GetAllDeclarations(SyntaxNode syntax) { var finder = new DeclarationFinder(); finder.Visit(syntax); return finder._map; } private void Add(SyntaxToken syntaxToken) { if (syntaxToken.Kind() == SyntaxKind.IdentifierToken) { var identifier = syntaxToken.ValueText; if (!_map.TryGetValue(identifier, out var list)) { list = new List<SyntaxToken>(); _map.Add(identifier, list); } list.Add(syntaxToken); } } public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { base.VisitVariableDeclarator(node); Add(node.Identifier); } public override void VisitCatchDeclaration(CatchDeclarationSyntax node) { base.VisitCatchDeclaration(node); Add(node.Identifier); } public override void VisitParameter(ParameterSyntax node) { base.VisitParameter(node); Add(node.Identifier); } public override void VisitFromClause(FromClauseSyntax node) { base.VisitFromClause(node); Add(node.Identifier); } public override void VisitLetClause(LetClauseSyntax node) { base.VisitLetClause(node); Add(node.Identifier); } public override void VisitJoinClause(JoinClauseSyntax node) { base.VisitJoinClause(node); Add(node.Identifier); } public override void VisitJoinIntoClause(JoinIntoClauseSyntax node) { base.VisitJoinIntoClause(node); Add(node.Identifier); } public override void VisitQueryContinuation(QueryContinuationSyntax node) { base.VisitQueryContinuation(node); Add(node.Identifier); } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DisableKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 DisableKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DisableKeywordRecommender() : base(SyntaxKind.DisableKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); if (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken) { // # nullable | // # nullable d| return true; } // # pragma warning | // # pragma warning d| return previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 DisableKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DisableKeywordRecommender() : base(SyntaxKind.DisableKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); if (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken) { // # nullable | // # nullable d| return true; } // # pragma warning | // # pragma warning d| return previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Test/Syntax/LexicalAndXml/NameAttributeValueLexerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameAttributeValueLexerTests : DocumentationCommentLexerTestBase { [Fact] public void TestLexIdentifiers() { // NOTE: Dev11 doesn't support unicode escapes (\u), but there doesn't seem // to be a good reason to do extra work to forbid them in Roslyn. AssertTokens("a", Token(SyntaxKind.IdentifierToken, "a")); AssertTokens("\u0061", Token(SyntaxKind.IdentifierToken, "\u0061", "a")); AssertTokens("&#x61;", Token(SyntaxKind.IdentifierToken, "&#x61;", "a")); AssertTokens("ab", Token(SyntaxKind.IdentifierToken, "ab")); AssertTokens("\u0061b", Token(SyntaxKind.IdentifierToken, "\u0061b", "ab")); AssertTokens("a\u0062", Token(SyntaxKind.IdentifierToken, "a\u0062", "ab")); AssertTokens("&#x61;b", Token(SyntaxKind.IdentifierToken, "&#x61;b", "ab")); AssertTokens("a&#x62;", Token(SyntaxKind.IdentifierToken, "a&#x62;", "ab")); } [Fact] public void TestLexKeywords() { // NOTE: treat keywords as identifiers. AssertTokens("global", Token(SyntaxKind.IdentifierToken, "global")); AssertTokens("operator", Token(SyntaxKind.IdentifierToken, "operator")); AssertTokens("explicit", Token(SyntaxKind.IdentifierToken, "explicit")); AssertTokens("implicit", Token(SyntaxKind.IdentifierToken, "implicit")); AssertTokens("ref", Token(SyntaxKind.IdentifierToken, "ref")); AssertTokens("out", Token(SyntaxKind.IdentifierToken, "out")); AssertTokens("true", Token(SyntaxKind.IdentifierToken, "true")); AssertTokens("false", Token(SyntaxKind.IdentifierToken, "false")); AssertTokens("&#103;lobal", Token(SyntaxKind.IdentifierToken, "&#103;lobal", "global")); AssertTokens("&#111;perator", Token(SyntaxKind.IdentifierToken, "&#111;perator", "operator")); AssertTokens("&#101;xplicit", Token(SyntaxKind.IdentifierToken, "&#101;xplicit", "explicit")); AssertTokens("&#105;mplicit", Token(SyntaxKind.IdentifierToken, "&#105;mplicit", "implicit")); AssertTokens("&#114;ef", Token(SyntaxKind.IdentifierToken, "&#114;ef", "ref")); AssertTokens("&#111;ut", Token(SyntaxKind.IdentifierToken, "&#111;ut", "out")); AssertTokens("&#116;rue", Token(SyntaxKind.IdentifierToken, "&#116;rue", "true")); AssertTokens("&#102;alse", Token(SyntaxKind.IdentifierToken, "&#102;alse", "false")); AssertTokens("&#103;loba&#108;", Token(SyntaxKind.IdentifierToken, "&#103;loba&#108;", "global")); AssertTokens("&#111;perato&#114;", Token(SyntaxKind.IdentifierToken, "&#111;perato&#114;", "operator")); AssertTokens("&#101;xplici&#116;", Token(SyntaxKind.IdentifierToken, "&#101;xplici&#116;", "explicit")); AssertTokens("&#105;mplici&#116;", Token(SyntaxKind.IdentifierToken, "&#105;mplici&#116;", "implicit")); AssertTokens("&#114;e&#102;", Token(SyntaxKind.IdentifierToken, "&#114;e&#102;", "ref")); AssertTokens("&#111;u&#116;", Token(SyntaxKind.IdentifierToken, "&#111;u&#116;", "out")); AssertTokens("&#116;ru&#101;", Token(SyntaxKind.IdentifierToken, "&#116;ru&#101;", "true")); AssertTokens("&#102;als&#101;", Token(SyntaxKind.IdentifierToken, "&#102;als&#101;", "false")); } [Fact] public void TestLexVerbatimKeywords() { AssertTokens("@global", Token(SyntaxKind.IdentifierToken, "@global")); AssertTokens("@operator", Token(SyntaxKind.IdentifierToken, "@operator")); AssertTokens("@explicit", Token(SyntaxKind.IdentifierToken, "@explicit")); AssertTokens("@implicit", Token(SyntaxKind.IdentifierToken, "@implicit")); AssertTokens("@ref", Token(SyntaxKind.IdentifierToken, "@ref")); AssertTokens("@out", Token(SyntaxKind.IdentifierToken, "@out")); AssertTokens("@true", Token(SyntaxKind.IdentifierToken, "@true")); AssertTokens("@false", Token(SyntaxKind.IdentifierToken, "@false")); AssertTokens("&#64;global", Token(SyntaxKind.IdentifierToken, "&#64;global", "@global")); AssertTokens("&#64;operator", Token(SyntaxKind.IdentifierToken, "&#64;operator", "@operator")); AssertTokens("&#64;explicit", Token(SyntaxKind.IdentifierToken, "&#64;explicit", "@explicit")); AssertTokens("&#64;implicit", Token(SyntaxKind.IdentifierToken, "&#64;implicit", "@implicit")); AssertTokens("&#64;ref", Token(SyntaxKind.IdentifierToken, "&#64;ref", "@ref")); AssertTokens("&#64;out", Token(SyntaxKind.IdentifierToken, "&#64;out", "@out")); AssertTokens("&#64;true", Token(SyntaxKind.IdentifierToken, "&#64;true", "@true")); AssertTokens("&#64;false", Token(SyntaxKind.IdentifierToken, "&#64;false", "@false")); } [Fact] public void TestLexUnicodeEscapeKeywords() { AssertTokens("\\u0067lobal", Token(SyntaxKind.IdentifierToken, "\\u0067lobal", "global")); AssertTokens("\\u006Fperator", Token(SyntaxKind.IdentifierToken, "\\u006Fperator", "operator")); AssertTokens("\\u0065xplicit", Token(SyntaxKind.IdentifierToken, "\\u0065xplicit", "explicit")); AssertTokens("\\u0069mplicit", Token(SyntaxKind.IdentifierToken, "\\u0069mplicit", "implicit")); AssertTokens("\\u0072ef", Token(SyntaxKind.IdentifierToken, "\\u0072ef", "ref")); AssertTokens("\\u006Fut", Token(SyntaxKind.IdentifierToken, "\\u006Fut", "out")); AssertTokens("\\u0074rue", Token(SyntaxKind.IdentifierToken, "\\u0074rue", "true")); AssertTokens("\\u0066alse", Token(SyntaxKind.IdentifierToken, "\\u0066alse", "false")); } [WorkItem(530519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530519")] [Fact] public void TestLexUnicodeEscapeKeywordsWithEntities() { // BREAK: Dev11 treats these as verbatim identifiers. AssertTokens("&#92;u0067lobal", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0067lobal")); AssertTokens("&#92;u006Fperator", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u006Fperator")); AssertTokens("&#92;u0065xplicit", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0065xplicit")); AssertTokens("&#92;u0069mplicit", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0069mplicit")); AssertTokens("&#92;u0072ef", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0072ef")); AssertTokens("&#92;u006Fut", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u006Fut")); AssertTokens("&#92;u0074rue", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0074rue")); AssertTokens("&#92;u0066alse", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0066alse")); } [Fact] public void TestLexPunctuation() { AssertTokens(".", Token(SyntaxKind.DotToken)); AssertTokens(",", Token(SyntaxKind.CommaToken)); AssertTokens(":", Token(SyntaxKind.ColonToken)); AssertTokens("::", Token(SyntaxKind.ColonColonToken)); AssertTokens("(", Token(SyntaxKind.OpenParenToken)); AssertTokens(")", Token(SyntaxKind.CloseParenToken)); AssertTokens("[", Token(SyntaxKind.OpenBracketToken)); AssertTokens("]", Token(SyntaxKind.CloseBracketToken)); AssertTokens("?", Token(SyntaxKind.QuestionToken)); AssertTokens("??", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); AssertTokens("*", Token(SyntaxKind.AsteriskToken)); AssertTokens("<", Token(SyntaxKind.BadToken, "<")); //illegal in attribute AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); // Special case: curly brackets become angle brackets. AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("}", Token(SyntaxKind.GreaterThanToken, "}", ">")); AssertTokens("&#46;", Token(SyntaxKind.DotToken, "&#46;", ".")); AssertTokens("&#44;", Token(SyntaxKind.CommaToken, "&#44;", ",")); //AssertTokens("&#58;", Token(SyntaxKind.ColonToken, "&#46;", ":")); //not needed AssertTokens("&#58;&#58;", Token(SyntaxKind.ColonColonToken, "&#58;&#58;", "::")); AssertTokens("&#58;:", Token(SyntaxKind.ColonColonToken, "&#58;:", "::")); AssertTokens(":&#58;", Token(SyntaxKind.ColonColonToken, ":&#58;", "::")); AssertTokens("&#40;", Token(SyntaxKind.OpenParenToken, "&#40;", "(")); AssertTokens("&#41;", Token(SyntaxKind.CloseParenToken, "&#41;", ")")); AssertTokens("&#91;", Token(SyntaxKind.OpenBracketToken, "&#91;", "[")); AssertTokens("&#93;", Token(SyntaxKind.CloseBracketToken, "&#93;", "]")); AssertTokens("&#63;", Token(SyntaxKind.QuestionToken, "&#63;", "?")); AssertTokens("&#63;&#63;", Token(SyntaxKind.QuestionToken, "&#63;", "?"), Token(SyntaxKind.QuestionToken, "&#63;", "?")); AssertTokens("&#42;", Token(SyntaxKind.AsteriskToken, "&#42;", "*")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); // Special case: curly brackets become angle brackets. AssertTokens("&#123;", Token(SyntaxKind.LessThanToken, "&#123;", "<")); AssertTokens("&#125;", Token(SyntaxKind.GreaterThanToken, "&#125;", ">")); } [Fact] public void TestLexPunctuationSequences() { AssertTokens(":::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonToken)); AssertTokens("::::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonColonToken)); AssertTokens(":::::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonToken)); // No null-coalescing in crefs AssertTokens("???", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); AssertTokens("????", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); } [Fact] public void TestLexPunctuationSpecial() { // These will just end up as skipped tokens, but there's no harm in testing them. AssertTokens("&amp;", Token(SyntaxKind.AmpersandToken, "&amp;", "&")); AssertTokens("&#38;", Token(SyntaxKind.AmpersandToken, "&#38;", "&")); AssertTokens("&#038;", Token(SyntaxKind.AmpersandToken, "&#038;", "&")); AssertTokens("&#0038;", Token(SyntaxKind.AmpersandToken, "&#0038;", "&")); AssertTokens("&#x26;", Token(SyntaxKind.AmpersandToken, "&#x26;", "&")); AssertTokens("&#x026;", Token(SyntaxKind.AmpersandToken, "&#x026;", "&")); AssertTokens("&#x0026;", Token(SyntaxKind.AmpersandToken, "&#x0026;", "&")); AssertTokens("&lt;", Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#060;", Token(SyntaxKind.LessThanToken, "&#060;", "<")); AssertTokens("&#0060;", Token(SyntaxKind.LessThanToken, "&#0060;", "<")); AssertTokens("&#x3C;", Token(SyntaxKind.LessThanToken, "&#x3C;", "<")); AssertTokens("&#x03C;", Token(SyntaxKind.LessThanToken, "&#x03C;", "<")); AssertTokens("&#x003C;", Token(SyntaxKind.LessThanToken, "&#x003C;", "<")); AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("&#123;", Token(SyntaxKind.LessThanToken, "&#123;", "<")); AssertTokens("&#0123;", Token(SyntaxKind.LessThanToken, "&#0123;", "<")); AssertTokens("&#x7B;", Token(SyntaxKind.LessThanToken, "&#x7B;", "<")); AssertTokens("&#x07B;", Token(SyntaxKind.LessThanToken, "&#x07B;", "<")); AssertTokens("&#x007B;", Token(SyntaxKind.LessThanToken, "&#x007B;", "<")); AssertTokens("&gt;", Token(SyntaxKind.GreaterThanToken, "&gt;", ">")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#062;", Token(SyntaxKind.GreaterThanToken, "&#062;", ">")); AssertTokens("&#0062;", Token(SyntaxKind.GreaterThanToken, "&#0062;", ">")); AssertTokens("&#x3E;", Token(SyntaxKind.GreaterThanToken, "&#x3E;", ">")); AssertTokens("&#x03E;", Token(SyntaxKind.GreaterThanToken, "&#x03E;", ">")); AssertTokens("&#x003E;", Token(SyntaxKind.GreaterThanToken, "&#x003E;", ">")); AssertTokens("}", Token(SyntaxKind.GreaterThanToken, "}", ">")); AssertTokens("&#125;", Token(SyntaxKind.GreaterThanToken, "&#125;", ">")); AssertTokens("&#0125;", Token(SyntaxKind.GreaterThanToken, "&#0125;", ">")); AssertTokens("&#x7D;", Token(SyntaxKind.GreaterThanToken, "&#x7D;", ">")); AssertTokens("&#x07D;", Token(SyntaxKind.GreaterThanToken, "&#x07D;", ">")); AssertTokens("&#x007D;", Token(SyntaxKind.GreaterThanToken, "&#x007D;", ">")); } [Fact] public void TestLexOperators() { // Single-character AssertTokens("&", Token(SyntaxKind.XmlEntityLiteralToken, "&")); // Not valid XML AssertTokens("~", Token(SyntaxKind.TildeToken)); AssertTokens("*", Token(SyntaxKind.AsteriskToken)); AssertTokens("/", Token(SyntaxKind.SlashToken)); AssertTokens("%", Token(SyntaxKind.PercentToken)); AssertTokens("|", Token(SyntaxKind.BarToken)); AssertTokens("^", Token(SyntaxKind.CaretToken)); // Multi-character AssertTokens("+", Token(SyntaxKind.PlusToken)); AssertTokens("++", Token(SyntaxKind.PlusPlusToken)); AssertTokens("-", Token(SyntaxKind.MinusToken)); AssertTokens("--", Token(SyntaxKind.MinusMinusToken)); AssertTokens("<", Token(SyntaxKind.BadToken, "<")); AssertTokens("<<", Token(SyntaxKind.BadToken, "<"), Token(SyntaxKind.BadToken, "<")); AssertTokens("<=", Token(SyntaxKind.BadToken, "<"), Token(SyntaxKind.EqualsToken)); AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">=", Token(SyntaxKind.GreaterThanEqualsToken)); AssertTokens("=", Token(SyntaxKind.EqualsToken)); AssertTokens("==", Token(SyntaxKind.EqualsEqualsToken)); AssertTokens("!", Token(SyntaxKind.ExclamationToken)); AssertTokens("!=", Token(SyntaxKind.ExclamationEqualsToken)); // Single-character AssertTokens("&#38;", Token(SyntaxKind.AmpersandToken, "&#38;", "&")); // Fine AssertTokens("&#126;", Token(SyntaxKind.TildeToken, "&#126;", "~")); AssertTokens("&#42;", Token(SyntaxKind.AsteriskToken, "&#42;", "*")); AssertTokens("&#47;", Token(SyntaxKind.SlashToken, "&#47;", "/")); AssertTokens("&#37;", Token(SyntaxKind.PercentToken, "&#37;", "%")); AssertTokens("&#124;", Token(SyntaxKind.BarToken, "&#124;", "|")); AssertTokens("&#94;", Token(SyntaxKind.CaretToken, "&#94;", "^")); // Multi-character AssertTokens("&#43;", Token(SyntaxKind.PlusToken, "&#43;", "+")); AssertTokens("+&#43;", Token(SyntaxKind.PlusPlusToken, "+&#43;", "++")); AssertTokens("&#43;+", Token(SyntaxKind.PlusPlusToken, "&#43;+", "++")); AssertTokens("&#43;&#43;", Token(SyntaxKind.PlusPlusToken, "&#43;&#43;", "++")); AssertTokens("&#45;", Token(SyntaxKind.MinusToken, "&#45;", "-")); AssertTokens("-&#45;", Token(SyntaxKind.MinusMinusToken, "-&#45;", "--")); AssertTokens("&#45;-", Token(SyntaxKind.MinusMinusToken, "&#45;-", "--")); AssertTokens("&#45;&#45;", Token(SyntaxKind.MinusMinusToken, "&#45;&#45;", "--")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#60;&#60;", Token(SyntaxKind.LessThanLessThanToken, "&#60;&#60;", "<<")); AssertTokens("&#60;=", Token(SyntaxKind.LessThanEqualsToken, "&#60;=", "<=")); AssertTokens("&#60;&#61;", Token(SyntaxKind.LessThanEqualsToken, "&#60;&#61;", "<=")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens(">&#62;", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#62;>", Token(SyntaxKind.GreaterThanToken, "&#62;", ">"), Token(SyntaxKind.GreaterThanToken)); AssertTokens("&#62;&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">"), Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#62;=", Token(SyntaxKind.GreaterThanEqualsToken, "&#62;=", ">=")); AssertTokens(">&#61;", Token(SyntaxKind.GreaterThanEqualsToken, ">&#61;", ">=")); AssertTokens("&#62;&#61;", Token(SyntaxKind.GreaterThanEqualsToken, "&#62;&#61;", ">=")); AssertTokens("&#61;", Token(SyntaxKind.EqualsToken, "&#61;", "=")); AssertTokens("=&#61;", Token(SyntaxKind.EqualsEqualsToken, "=&#61;", "==")); AssertTokens("&#61;=", Token(SyntaxKind.EqualsEqualsToken, "&#61;=", "==")); AssertTokens("&#61;&#61;", Token(SyntaxKind.EqualsEqualsToken, "&#61;&#61;", "==")); AssertTokens("&#33;", Token(SyntaxKind.ExclamationToken, "&#33;", "!")); AssertTokens("!&#61;", Token(SyntaxKind.ExclamationEqualsToken, "!&#61;", "!=")); AssertTokens("&#33;=", Token(SyntaxKind.ExclamationEqualsToken, "&#33;=", "!=")); AssertTokens("&#33;&#61;", Token(SyntaxKind.ExclamationEqualsToken, "&#33;&#61;", "!=")); } [Fact] public void TestLexOperatorSequence() { AssertTokens("+++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusToken)); AssertTokens("++++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusPlusToken)); AssertTokens("+++++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusToken)); AssertTokens("---", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusToken)); AssertTokens("----", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusMinusToken)); AssertTokens("-----", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusToken)); AssertTokens("===", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("====", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsEqualsToken)); AssertTokens("=====", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens("&lt;&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<")); AssertTokens("&lt;&lt;&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens(">>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>>>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens("!!=", Token(SyntaxKind.ExclamationToken), Token(SyntaxKind.ExclamationEqualsToken)); AssertTokens("&lt;&lt;=", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.EqualsToken)); AssertTokens(">>=", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanEqualsToken)); //fixed up by parser AssertTokens("!==", Token(SyntaxKind.ExclamationEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("&lt;==", Token(SyntaxKind.LessThanEqualsToken, "&lt;=", "<="), Token(SyntaxKind.EqualsToken)); AssertTokens(">==", Token(SyntaxKind.GreaterThanEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<")); AssertTokens("{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("{{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanLessThanToken, "{{", "<<")); AssertTokens("{{{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanToken, "{", "<")); } [Fact] public void TestLexBadEntity() { // These will just end up as skipped tokens, but there's no harm in testing them. // Bad xml entities AssertTokens("&", Token(SyntaxKind.XmlEntityLiteralToken, "&")); AssertTokens("&&", Token(SyntaxKind.XmlEntityLiteralToken, "&"), Token(SyntaxKind.XmlEntityLiteralToken, "&")); AssertTokens("&;", Token(SyntaxKind.XmlEntityLiteralToken, "&;")); AssertTokens("&a;", Token(SyntaxKind.XmlEntityLiteralToken, "&a;")); AssertTokens("&#;", Token(SyntaxKind.XmlEntityLiteralToken, "&#;")); AssertTokens("&#x;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x;")); AssertTokens("&#a;", Token(SyntaxKind.XmlEntityLiteralToken, "&#"), Token(SyntaxKind.IdentifierToken, "a"), Token(SyntaxKind.BadToken, ";")); AssertTokens("&#xg;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x"), Token(SyntaxKind.IdentifierToken, "g"), Token(SyntaxKind.BadToken, ";")); // Overflowing entities AssertTokens("&#99999999999999999999;", Token(SyntaxKind.XmlEntityLiteralToken, "&#99999999999999999999;")); AssertTokens("&#x99999999999999999999;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x99999999999999999999;")); // Long but not overflowing entities AssertTokens("&#00000000000000000097;", Token(SyntaxKind.IdentifierToken, "&#00000000000000000097;", "a")); AssertTokens("&#x00000000000000000061;", Token(SyntaxKind.IdentifierToken, "&#x00000000000000000061;", "a")); } [Fact] public void TestLexBadXml() { AssertTokens("<", Token(SyntaxKind.BadToken, "<")); AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); } [Fact] public void TestLexEmpty() { AssertTokens(""); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexNewline() { AssertTokens(@"A .B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); AssertTokens(@"A&#10;.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexEntityInTrivia() { AssertTokens(@"A&#32;.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexCSharpTrivia() { AssertTokens(@"A //comment .B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); AssertTokens(@"A /*comment*/.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } internal override IEnumerable<InternalSyntax.SyntaxToken> GetTokens(string text) { Assert.DoesNotContain("'", text, StringComparison.Ordinal); using (var lexer = new InternalSyntax.Lexer(SourceText.From(text + "'"), TestOptions.RegularWithDocumentationComments)) { while (true) { var token = lexer.Lex(InternalSyntax.LexerMode.XmlNameQuote | InternalSyntax.LexerMode.XmlDocCommentStyleSingleLine | InternalSyntax.LexerMode.XmlDocCommentLocationInterior); if (token.Kind == SyntaxKind.SingleQuoteToken) { break; } yield return token; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameAttributeValueLexerTests : DocumentationCommentLexerTestBase { [Fact] public void TestLexIdentifiers() { // NOTE: Dev11 doesn't support unicode escapes (\u), but there doesn't seem // to be a good reason to do extra work to forbid them in Roslyn. AssertTokens("a", Token(SyntaxKind.IdentifierToken, "a")); AssertTokens("\u0061", Token(SyntaxKind.IdentifierToken, "\u0061", "a")); AssertTokens("&#x61;", Token(SyntaxKind.IdentifierToken, "&#x61;", "a")); AssertTokens("ab", Token(SyntaxKind.IdentifierToken, "ab")); AssertTokens("\u0061b", Token(SyntaxKind.IdentifierToken, "\u0061b", "ab")); AssertTokens("a\u0062", Token(SyntaxKind.IdentifierToken, "a\u0062", "ab")); AssertTokens("&#x61;b", Token(SyntaxKind.IdentifierToken, "&#x61;b", "ab")); AssertTokens("a&#x62;", Token(SyntaxKind.IdentifierToken, "a&#x62;", "ab")); } [Fact] public void TestLexKeywords() { // NOTE: treat keywords as identifiers. AssertTokens("global", Token(SyntaxKind.IdentifierToken, "global")); AssertTokens("operator", Token(SyntaxKind.IdentifierToken, "operator")); AssertTokens("explicit", Token(SyntaxKind.IdentifierToken, "explicit")); AssertTokens("implicit", Token(SyntaxKind.IdentifierToken, "implicit")); AssertTokens("ref", Token(SyntaxKind.IdentifierToken, "ref")); AssertTokens("out", Token(SyntaxKind.IdentifierToken, "out")); AssertTokens("true", Token(SyntaxKind.IdentifierToken, "true")); AssertTokens("false", Token(SyntaxKind.IdentifierToken, "false")); AssertTokens("&#103;lobal", Token(SyntaxKind.IdentifierToken, "&#103;lobal", "global")); AssertTokens("&#111;perator", Token(SyntaxKind.IdentifierToken, "&#111;perator", "operator")); AssertTokens("&#101;xplicit", Token(SyntaxKind.IdentifierToken, "&#101;xplicit", "explicit")); AssertTokens("&#105;mplicit", Token(SyntaxKind.IdentifierToken, "&#105;mplicit", "implicit")); AssertTokens("&#114;ef", Token(SyntaxKind.IdentifierToken, "&#114;ef", "ref")); AssertTokens("&#111;ut", Token(SyntaxKind.IdentifierToken, "&#111;ut", "out")); AssertTokens("&#116;rue", Token(SyntaxKind.IdentifierToken, "&#116;rue", "true")); AssertTokens("&#102;alse", Token(SyntaxKind.IdentifierToken, "&#102;alse", "false")); AssertTokens("&#103;loba&#108;", Token(SyntaxKind.IdentifierToken, "&#103;loba&#108;", "global")); AssertTokens("&#111;perato&#114;", Token(SyntaxKind.IdentifierToken, "&#111;perato&#114;", "operator")); AssertTokens("&#101;xplici&#116;", Token(SyntaxKind.IdentifierToken, "&#101;xplici&#116;", "explicit")); AssertTokens("&#105;mplici&#116;", Token(SyntaxKind.IdentifierToken, "&#105;mplici&#116;", "implicit")); AssertTokens("&#114;e&#102;", Token(SyntaxKind.IdentifierToken, "&#114;e&#102;", "ref")); AssertTokens("&#111;u&#116;", Token(SyntaxKind.IdentifierToken, "&#111;u&#116;", "out")); AssertTokens("&#116;ru&#101;", Token(SyntaxKind.IdentifierToken, "&#116;ru&#101;", "true")); AssertTokens("&#102;als&#101;", Token(SyntaxKind.IdentifierToken, "&#102;als&#101;", "false")); } [Fact] public void TestLexVerbatimKeywords() { AssertTokens("@global", Token(SyntaxKind.IdentifierToken, "@global")); AssertTokens("@operator", Token(SyntaxKind.IdentifierToken, "@operator")); AssertTokens("@explicit", Token(SyntaxKind.IdentifierToken, "@explicit")); AssertTokens("@implicit", Token(SyntaxKind.IdentifierToken, "@implicit")); AssertTokens("@ref", Token(SyntaxKind.IdentifierToken, "@ref")); AssertTokens("@out", Token(SyntaxKind.IdentifierToken, "@out")); AssertTokens("@true", Token(SyntaxKind.IdentifierToken, "@true")); AssertTokens("@false", Token(SyntaxKind.IdentifierToken, "@false")); AssertTokens("&#64;global", Token(SyntaxKind.IdentifierToken, "&#64;global", "@global")); AssertTokens("&#64;operator", Token(SyntaxKind.IdentifierToken, "&#64;operator", "@operator")); AssertTokens("&#64;explicit", Token(SyntaxKind.IdentifierToken, "&#64;explicit", "@explicit")); AssertTokens("&#64;implicit", Token(SyntaxKind.IdentifierToken, "&#64;implicit", "@implicit")); AssertTokens("&#64;ref", Token(SyntaxKind.IdentifierToken, "&#64;ref", "@ref")); AssertTokens("&#64;out", Token(SyntaxKind.IdentifierToken, "&#64;out", "@out")); AssertTokens("&#64;true", Token(SyntaxKind.IdentifierToken, "&#64;true", "@true")); AssertTokens("&#64;false", Token(SyntaxKind.IdentifierToken, "&#64;false", "@false")); } [Fact] public void TestLexUnicodeEscapeKeywords() { AssertTokens("\\u0067lobal", Token(SyntaxKind.IdentifierToken, "\\u0067lobal", "global")); AssertTokens("\\u006Fperator", Token(SyntaxKind.IdentifierToken, "\\u006Fperator", "operator")); AssertTokens("\\u0065xplicit", Token(SyntaxKind.IdentifierToken, "\\u0065xplicit", "explicit")); AssertTokens("\\u0069mplicit", Token(SyntaxKind.IdentifierToken, "\\u0069mplicit", "implicit")); AssertTokens("\\u0072ef", Token(SyntaxKind.IdentifierToken, "\\u0072ef", "ref")); AssertTokens("\\u006Fut", Token(SyntaxKind.IdentifierToken, "\\u006Fut", "out")); AssertTokens("\\u0074rue", Token(SyntaxKind.IdentifierToken, "\\u0074rue", "true")); AssertTokens("\\u0066alse", Token(SyntaxKind.IdentifierToken, "\\u0066alse", "false")); } [WorkItem(530519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530519")] [Fact] public void TestLexUnicodeEscapeKeywordsWithEntities() { // BREAK: Dev11 treats these as verbatim identifiers. AssertTokens("&#92;u0067lobal", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0067lobal")); AssertTokens("&#92;u006Fperator", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u006Fperator")); AssertTokens("&#92;u0065xplicit", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0065xplicit")); AssertTokens("&#92;u0069mplicit", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0069mplicit")); AssertTokens("&#92;u0072ef", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0072ef")); AssertTokens("&#92;u006Fut", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u006Fut")); AssertTokens("&#92;u0074rue", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0074rue")); AssertTokens("&#92;u0066alse", Token(SyntaxKind.XmlEntityLiteralToken, "&#92;", "\\"), Token(SyntaxKind.IdentifierToken, "u0066alse")); } [Fact] public void TestLexPunctuation() { AssertTokens(".", Token(SyntaxKind.DotToken)); AssertTokens(",", Token(SyntaxKind.CommaToken)); AssertTokens(":", Token(SyntaxKind.ColonToken)); AssertTokens("::", Token(SyntaxKind.ColonColonToken)); AssertTokens("(", Token(SyntaxKind.OpenParenToken)); AssertTokens(")", Token(SyntaxKind.CloseParenToken)); AssertTokens("[", Token(SyntaxKind.OpenBracketToken)); AssertTokens("]", Token(SyntaxKind.CloseBracketToken)); AssertTokens("?", Token(SyntaxKind.QuestionToken)); AssertTokens("??", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); AssertTokens("*", Token(SyntaxKind.AsteriskToken)); AssertTokens("<", Token(SyntaxKind.BadToken, "<")); //illegal in attribute AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); // Special case: curly brackets become angle brackets. AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("}", Token(SyntaxKind.GreaterThanToken, "}", ">")); AssertTokens("&#46;", Token(SyntaxKind.DotToken, "&#46;", ".")); AssertTokens("&#44;", Token(SyntaxKind.CommaToken, "&#44;", ",")); //AssertTokens("&#58;", Token(SyntaxKind.ColonToken, "&#46;", ":")); //not needed AssertTokens("&#58;&#58;", Token(SyntaxKind.ColonColonToken, "&#58;&#58;", "::")); AssertTokens("&#58;:", Token(SyntaxKind.ColonColonToken, "&#58;:", "::")); AssertTokens(":&#58;", Token(SyntaxKind.ColonColonToken, ":&#58;", "::")); AssertTokens("&#40;", Token(SyntaxKind.OpenParenToken, "&#40;", "(")); AssertTokens("&#41;", Token(SyntaxKind.CloseParenToken, "&#41;", ")")); AssertTokens("&#91;", Token(SyntaxKind.OpenBracketToken, "&#91;", "[")); AssertTokens("&#93;", Token(SyntaxKind.CloseBracketToken, "&#93;", "]")); AssertTokens("&#63;", Token(SyntaxKind.QuestionToken, "&#63;", "?")); AssertTokens("&#63;&#63;", Token(SyntaxKind.QuestionToken, "&#63;", "?"), Token(SyntaxKind.QuestionToken, "&#63;", "?")); AssertTokens("&#42;", Token(SyntaxKind.AsteriskToken, "&#42;", "*")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); // Special case: curly brackets become angle brackets. AssertTokens("&#123;", Token(SyntaxKind.LessThanToken, "&#123;", "<")); AssertTokens("&#125;", Token(SyntaxKind.GreaterThanToken, "&#125;", ">")); } [Fact] public void TestLexPunctuationSequences() { AssertTokens(":::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonToken)); AssertTokens("::::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonColonToken)); AssertTokens(":::::", Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonColonToken), Token(SyntaxKind.ColonToken)); // No null-coalescing in crefs AssertTokens("???", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); AssertTokens("????", Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken), Token(SyntaxKind.QuestionToken)); } [Fact] public void TestLexPunctuationSpecial() { // These will just end up as skipped tokens, but there's no harm in testing them. AssertTokens("&amp;", Token(SyntaxKind.AmpersandToken, "&amp;", "&")); AssertTokens("&#38;", Token(SyntaxKind.AmpersandToken, "&#38;", "&")); AssertTokens("&#038;", Token(SyntaxKind.AmpersandToken, "&#038;", "&")); AssertTokens("&#0038;", Token(SyntaxKind.AmpersandToken, "&#0038;", "&")); AssertTokens("&#x26;", Token(SyntaxKind.AmpersandToken, "&#x26;", "&")); AssertTokens("&#x026;", Token(SyntaxKind.AmpersandToken, "&#x026;", "&")); AssertTokens("&#x0026;", Token(SyntaxKind.AmpersandToken, "&#x0026;", "&")); AssertTokens("&lt;", Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#060;", Token(SyntaxKind.LessThanToken, "&#060;", "<")); AssertTokens("&#0060;", Token(SyntaxKind.LessThanToken, "&#0060;", "<")); AssertTokens("&#x3C;", Token(SyntaxKind.LessThanToken, "&#x3C;", "<")); AssertTokens("&#x03C;", Token(SyntaxKind.LessThanToken, "&#x03C;", "<")); AssertTokens("&#x003C;", Token(SyntaxKind.LessThanToken, "&#x003C;", "<")); AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("&#123;", Token(SyntaxKind.LessThanToken, "&#123;", "<")); AssertTokens("&#0123;", Token(SyntaxKind.LessThanToken, "&#0123;", "<")); AssertTokens("&#x7B;", Token(SyntaxKind.LessThanToken, "&#x7B;", "<")); AssertTokens("&#x07B;", Token(SyntaxKind.LessThanToken, "&#x07B;", "<")); AssertTokens("&#x007B;", Token(SyntaxKind.LessThanToken, "&#x007B;", "<")); AssertTokens("&gt;", Token(SyntaxKind.GreaterThanToken, "&gt;", ">")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#062;", Token(SyntaxKind.GreaterThanToken, "&#062;", ">")); AssertTokens("&#0062;", Token(SyntaxKind.GreaterThanToken, "&#0062;", ">")); AssertTokens("&#x3E;", Token(SyntaxKind.GreaterThanToken, "&#x3E;", ">")); AssertTokens("&#x03E;", Token(SyntaxKind.GreaterThanToken, "&#x03E;", ">")); AssertTokens("&#x003E;", Token(SyntaxKind.GreaterThanToken, "&#x003E;", ">")); AssertTokens("}", Token(SyntaxKind.GreaterThanToken, "}", ">")); AssertTokens("&#125;", Token(SyntaxKind.GreaterThanToken, "&#125;", ">")); AssertTokens("&#0125;", Token(SyntaxKind.GreaterThanToken, "&#0125;", ">")); AssertTokens("&#x7D;", Token(SyntaxKind.GreaterThanToken, "&#x7D;", ">")); AssertTokens("&#x07D;", Token(SyntaxKind.GreaterThanToken, "&#x07D;", ">")); AssertTokens("&#x007D;", Token(SyntaxKind.GreaterThanToken, "&#x007D;", ">")); } [Fact] public void TestLexOperators() { // Single-character AssertTokens("&", Token(SyntaxKind.XmlEntityLiteralToken, "&")); // Not valid XML AssertTokens("~", Token(SyntaxKind.TildeToken)); AssertTokens("*", Token(SyntaxKind.AsteriskToken)); AssertTokens("/", Token(SyntaxKind.SlashToken)); AssertTokens("%", Token(SyntaxKind.PercentToken)); AssertTokens("|", Token(SyntaxKind.BarToken)); AssertTokens("^", Token(SyntaxKind.CaretToken)); // Multi-character AssertTokens("+", Token(SyntaxKind.PlusToken)); AssertTokens("++", Token(SyntaxKind.PlusPlusToken)); AssertTokens("-", Token(SyntaxKind.MinusToken)); AssertTokens("--", Token(SyntaxKind.MinusMinusToken)); AssertTokens("<", Token(SyntaxKind.BadToken, "<")); AssertTokens("<<", Token(SyntaxKind.BadToken, "<"), Token(SyntaxKind.BadToken, "<")); AssertTokens("<=", Token(SyntaxKind.BadToken, "<"), Token(SyntaxKind.EqualsToken)); AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">=", Token(SyntaxKind.GreaterThanEqualsToken)); AssertTokens("=", Token(SyntaxKind.EqualsToken)); AssertTokens("==", Token(SyntaxKind.EqualsEqualsToken)); AssertTokens("!", Token(SyntaxKind.ExclamationToken)); AssertTokens("!=", Token(SyntaxKind.ExclamationEqualsToken)); // Single-character AssertTokens("&#38;", Token(SyntaxKind.AmpersandToken, "&#38;", "&")); // Fine AssertTokens("&#126;", Token(SyntaxKind.TildeToken, "&#126;", "~")); AssertTokens("&#42;", Token(SyntaxKind.AsteriskToken, "&#42;", "*")); AssertTokens("&#47;", Token(SyntaxKind.SlashToken, "&#47;", "/")); AssertTokens("&#37;", Token(SyntaxKind.PercentToken, "&#37;", "%")); AssertTokens("&#124;", Token(SyntaxKind.BarToken, "&#124;", "|")); AssertTokens("&#94;", Token(SyntaxKind.CaretToken, "&#94;", "^")); // Multi-character AssertTokens("&#43;", Token(SyntaxKind.PlusToken, "&#43;", "+")); AssertTokens("+&#43;", Token(SyntaxKind.PlusPlusToken, "+&#43;", "++")); AssertTokens("&#43;+", Token(SyntaxKind.PlusPlusToken, "&#43;+", "++")); AssertTokens("&#43;&#43;", Token(SyntaxKind.PlusPlusToken, "&#43;&#43;", "++")); AssertTokens("&#45;", Token(SyntaxKind.MinusToken, "&#45;", "-")); AssertTokens("-&#45;", Token(SyntaxKind.MinusMinusToken, "-&#45;", "--")); AssertTokens("&#45;-", Token(SyntaxKind.MinusMinusToken, "&#45;-", "--")); AssertTokens("&#45;&#45;", Token(SyntaxKind.MinusMinusToken, "&#45;&#45;", "--")); AssertTokens("&#60;", Token(SyntaxKind.LessThanToken, "&#60;", "<")); AssertTokens("&#60;&#60;", Token(SyntaxKind.LessThanLessThanToken, "&#60;&#60;", "<<")); AssertTokens("&#60;=", Token(SyntaxKind.LessThanEqualsToken, "&#60;=", "<=")); AssertTokens("&#60;&#61;", Token(SyntaxKind.LessThanEqualsToken, "&#60;&#61;", "<=")); AssertTokens("&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens(">&#62;", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#62;>", Token(SyntaxKind.GreaterThanToken, "&#62;", ">"), Token(SyntaxKind.GreaterThanToken)); AssertTokens("&#62;&#62;", Token(SyntaxKind.GreaterThanToken, "&#62;", ">"), Token(SyntaxKind.GreaterThanToken, "&#62;", ">")); AssertTokens("&#62;=", Token(SyntaxKind.GreaterThanEqualsToken, "&#62;=", ">=")); AssertTokens(">&#61;", Token(SyntaxKind.GreaterThanEqualsToken, ">&#61;", ">=")); AssertTokens("&#62;&#61;", Token(SyntaxKind.GreaterThanEqualsToken, "&#62;&#61;", ">=")); AssertTokens("&#61;", Token(SyntaxKind.EqualsToken, "&#61;", "=")); AssertTokens("=&#61;", Token(SyntaxKind.EqualsEqualsToken, "=&#61;", "==")); AssertTokens("&#61;=", Token(SyntaxKind.EqualsEqualsToken, "&#61;=", "==")); AssertTokens("&#61;&#61;", Token(SyntaxKind.EqualsEqualsToken, "&#61;&#61;", "==")); AssertTokens("&#33;", Token(SyntaxKind.ExclamationToken, "&#33;", "!")); AssertTokens("!&#61;", Token(SyntaxKind.ExclamationEqualsToken, "!&#61;", "!=")); AssertTokens("&#33;=", Token(SyntaxKind.ExclamationEqualsToken, "&#33;=", "!=")); AssertTokens("&#33;&#61;", Token(SyntaxKind.ExclamationEqualsToken, "&#33;&#61;", "!=")); } [Fact] public void TestLexOperatorSequence() { AssertTokens("+++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusToken)); AssertTokens("++++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusPlusToken)); AssertTokens("+++++", Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusPlusToken), Token(SyntaxKind.PlusToken)); AssertTokens("---", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusToken)); AssertTokens("----", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusMinusToken)); AssertTokens("-----", Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusMinusToken), Token(SyntaxKind.MinusToken)); AssertTokens("===", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("====", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsEqualsToken)); AssertTokens("=====", Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens("&lt;&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<")); AssertTokens("&lt;&lt;&lt;&lt;&lt;", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.LessThanToken, "&lt;", "<")); AssertTokens(">>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens(">>>>>", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanToken)); AssertTokens("!!=", Token(SyntaxKind.ExclamationToken), Token(SyntaxKind.ExclamationEqualsToken)); AssertTokens("&lt;&lt;=", Token(SyntaxKind.LessThanLessThanToken, "&lt;&lt;", "<<"), Token(SyntaxKind.EqualsToken)); AssertTokens(">>=", Token(SyntaxKind.GreaterThanToken), Token(SyntaxKind.GreaterThanEqualsToken)); //fixed up by parser AssertTokens("!==", Token(SyntaxKind.ExclamationEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("&lt;==", Token(SyntaxKind.LessThanEqualsToken, "&lt;=", "<="), Token(SyntaxKind.EqualsToken)); AssertTokens(">==", Token(SyntaxKind.GreaterThanEqualsToken), Token(SyntaxKind.EqualsToken)); AssertTokens("{", Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<")); AssertTokens("{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanToken, "{", "<")); AssertTokens("{{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanLessThanToken, "{{", "<<")); AssertTokens("{{{{{", Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanLessThanToken, "{{", "<<"), Token(SyntaxKind.LessThanToken, "{", "<")); } [Fact] public void TestLexBadEntity() { // These will just end up as skipped tokens, but there's no harm in testing them. // Bad xml entities AssertTokens("&", Token(SyntaxKind.XmlEntityLiteralToken, "&")); AssertTokens("&&", Token(SyntaxKind.XmlEntityLiteralToken, "&"), Token(SyntaxKind.XmlEntityLiteralToken, "&")); AssertTokens("&;", Token(SyntaxKind.XmlEntityLiteralToken, "&;")); AssertTokens("&a;", Token(SyntaxKind.XmlEntityLiteralToken, "&a;")); AssertTokens("&#;", Token(SyntaxKind.XmlEntityLiteralToken, "&#;")); AssertTokens("&#x;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x;")); AssertTokens("&#a;", Token(SyntaxKind.XmlEntityLiteralToken, "&#"), Token(SyntaxKind.IdentifierToken, "a"), Token(SyntaxKind.BadToken, ";")); AssertTokens("&#xg;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x"), Token(SyntaxKind.IdentifierToken, "g"), Token(SyntaxKind.BadToken, ";")); // Overflowing entities AssertTokens("&#99999999999999999999;", Token(SyntaxKind.XmlEntityLiteralToken, "&#99999999999999999999;")); AssertTokens("&#x99999999999999999999;", Token(SyntaxKind.XmlEntityLiteralToken, "&#x99999999999999999999;")); // Long but not overflowing entities AssertTokens("&#00000000000000000097;", Token(SyntaxKind.IdentifierToken, "&#00000000000000000097;", "a")); AssertTokens("&#x00000000000000000061;", Token(SyntaxKind.IdentifierToken, "&#x00000000000000000061;", "a")); } [Fact] public void TestLexBadXml() { AssertTokens("<", Token(SyntaxKind.BadToken, "<")); AssertTokens(">", Token(SyntaxKind.GreaterThanToken)); } [Fact] public void TestLexEmpty() { AssertTokens(""); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexNewline() { AssertTokens(@"A .B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); AssertTokens(@"A&#10;.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexEntityInTrivia() { AssertTokens(@"A&#32;.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } [WorkItem(530523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530523")] [Fact(Skip = "530523")] public void TestLexCSharpTrivia() { AssertTokens(@"A //comment .B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); AssertTokens(@"A /*comment*/.B", Token(SyntaxKind.IdentifierToken, "A"), Token(SyntaxKind.DotToken), Token(SyntaxKind.IdentifierToken, "B")); } internal override IEnumerable<InternalSyntax.SyntaxToken> GetTokens(string text) { Assert.DoesNotContain("'", text, StringComparison.Ordinal); using (var lexer = new InternalSyntax.Lexer(SourceText.From(text + "'"), TestOptions.RegularWithDocumentationComments)) { while (true) { var token = lexer.Lex(InternalSyntax.LexerMode.XmlNameQuote | InternalSyntax.LexerMode.XmlDocCommentStyleSingleLine | InternalSyntax.LexerMode.XmlDocCommentLocationInterior); if (token.Kind == SyntaxKind.SingleQuoteToken) { break; } yield return token; } } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxFactoryTests <Fact> Public Sub SyntaxTree() Dim text = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit(), encoding:=Nothing).GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub SyntaxTreeFromNode() Dim text = SyntaxFactory.CompilationUnit().SyntaxTree.GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub TestSpacingOnNullableDatetimeType() Dim node = SyntaxFactory.CompilationUnit().WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C")).WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.PropertyStatement("P").WithAsClause( SyntaxFactory.SimpleAsClause( SyntaxFactory.NullableType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntegerKeyword))))) })) })).NormalizeWhitespace() Dim expected = "Class C" & vbCrLf & vbCrLf & " Property P As Integer?" & vbCrLf & "End Class" & vbCrLf Assert.Equal(expected, node.ToFullString()) End Sub <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> <WorkItem(720708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720708")> Public Sub TestLiteralDefaultStringValues() ' string CheckLiteralToString("A", """A""") CheckLiteralToString(ChrW(7).ToString(), "ChrW(7)") CheckLiteralToString(ChrW(10).ToString(), "vbLf") ' char CheckLiteralToString("A"c, """A""c") CheckLiteralToString(ChrW(7), "ChrW(7)") CheckLiteralToString(ChrW(10), "vbLf") '' Unsupported in VB: byte, sbyte, ushort, short ' uint CheckLiteralToString(UInteger.MinValue, "0UI") CheckLiteralToString(UInteger.MaxValue, "4294967295UI") ' int CheckLiteralToString(0, "0") CheckLiteralToString(Integer.MinValue, "-2147483648") CheckLiteralToString(Integer.MaxValue, "2147483647") ' ulong CheckLiteralToString(ULong.MinValue, "0UL") CheckLiteralToString(ULong.MaxValue, "18446744073709551615UL") ' long CheckLiteralToString(0L, "0L") CheckLiteralToString(Long.MinValue, "-9223372036854775808L") CheckLiteralToString(Long.MaxValue, "9223372036854775807L") ' float CheckLiteralToString(0.0F, "0F") CheckLiteralToString(0.012345F, "0.012345F") #If NET472 Then CheckLiteralToString(Single.MaxValue, "3.40282347E+38F") #Else CheckLiteralToString(Single.MaxValue, "3.4028235E+38F") #End If ' double CheckLiteralToString(0.0, "0") CheckLiteralToString(0.012345, "0.012345") CheckLiteralToString(Double.MaxValue, "1.7976931348623157E+308") ' decimal CheckLiteralToString(0D, "0D") CheckLiteralToString(0.012345D, "0.012345D") CheckLiteralToString(Decimal.MaxValue, "79228162514264337593543950335D") End Sub Private Shared Sub CheckLiteralToString(value As Object, expected As String) Dim factoryType As System.Type = GetType(SyntaxFactory) Dim literalMethods = factoryType.GetMethods().Where(Function(m) m.Name = "Literal" AndAlso m.GetParameters().Count() = 1) Dim literalMethod = literalMethods.Single(Function(m) m.GetParameters().Single().ParameterType = value.GetType()) Assert.Equal(expected, literalMethod.Invoke(Nothing, {value}).ToString()) End Sub <Fact> Public Shared Sub TestParseTypeNameOptions() Dim options As VisualBasicParseOptions = TestOptions.Regular Dim code = " #If Variable String #Else Integer #End If" Dim type1 = SyntaxFactory.ParseTypeName(code, options:=options.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("Variable", "True"))) Assert.Equal("String", type1.ToString()) Dim type2 = SyntaxFactory.ParseTypeName(code, options:=options) Assert.Equal("Integer", type2.ToString()) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxFactoryTests <Fact> Public Sub SyntaxTree() Dim text = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit(), encoding:=Nothing).GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub SyntaxTreeFromNode() Dim text = SyntaxFactory.CompilationUnit().SyntaxTree.GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub TestSpacingOnNullableDatetimeType() Dim node = SyntaxFactory.CompilationUnit().WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C")).WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.PropertyStatement("P").WithAsClause( SyntaxFactory.SimpleAsClause( SyntaxFactory.NullableType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntegerKeyword))))) })) })).NormalizeWhitespace() Dim expected = "Class C" & vbCrLf & vbCrLf & " Property P As Integer?" & vbCrLf & "End Class" & vbCrLf Assert.Equal(expected, node.ToFullString()) End Sub <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> <WorkItem(720708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720708")> Public Sub TestLiteralDefaultStringValues() ' string CheckLiteralToString("A", """A""") CheckLiteralToString(ChrW(7).ToString(), "ChrW(7)") CheckLiteralToString(ChrW(10).ToString(), "vbLf") ' char CheckLiteralToString("A"c, """A""c") CheckLiteralToString(ChrW(7), "ChrW(7)") CheckLiteralToString(ChrW(10), "vbLf") '' Unsupported in VB: byte, sbyte, ushort, short ' uint CheckLiteralToString(UInteger.MinValue, "0UI") CheckLiteralToString(UInteger.MaxValue, "4294967295UI") ' int CheckLiteralToString(0, "0") CheckLiteralToString(Integer.MinValue, "-2147483648") CheckLiteralToString(Integer.MaxValue, "2147483647") ' ulong CheckLiteralToString(ULong.MinValue, "0UL") CheckLiteralToString(ULong.MaxValue, "18446744073709551615UL") ' long CheckLiteralToString(0L, "0L") CheckLiteralToString(Long.MinValue, "-9223372036854775808L") CheckLiteralToString(Long.MaxValue, "9223372036854775807L") ' float CheckLiteralToString(0.0F, "0F") CheckLiteralToString(0.012345F, "0.012345F") #If NET472 Then CheckLiteralToString(Single.MaxValue, "3.40282347E+38F") #Else CheckLiteralToString(Single.MaxValue, "3.4028235E+38F") #End If ' double CheckLiteralToString(0.0, "0") CheckLiteralToString(0.012345, "0.012345") CheckLiteralToString(Double.MaxValue, "1.7976931348623157E+308") ' decimal CheckLiteralToString(0D, "0D") CheckLiteralToString(0.012345D, "0.012345D") CheckLiteralToString(Decimal.MaxValue, "79228162514264337593543950335D") End Sub Private Shared Sub CheckLiteralToString(value As Object, expected As String) Dim factoryType As System.Type = GetType(SyntaxFactory) Dim literalMethods = factoryType.GetMethods().Where(Function(m) m.Name = "Literal" AndAlso m.GetParameters().Count() = 1) Dim literalMethod = literalMethods.Single(Function(m) m.GetParameters().Single().ParameterType = value.GetType()) Assert.Equal(expected, literalMethod.Invoke(Nothing, {value}).ToString()) End Sub <Fact> Public Shared Sub TestParseTypeNameOptions() Dim options As VisualBasicParseOptions = TestOptions.Regular Dim code = " #If Variable String #Else Integer #End If" Dim type1 = SyntaxFactory.ParseTypeName(code, options:=options.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("Variable", "True"))) Assert.Equal("String", type1.ToString()) Dim type2 = SyntaxFactory.ParseTypeName(code, options:=options) Assert.Equal("Integer", type2.ToString()) End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/LineCommit/CommitWithViewTests.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.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit <[UseExportProvider]> Public Class CommitWithViewTests <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitAfterTypingAndDownArrow() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>imports $$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("System") testData.EditorOperations.MoveLineDown(extendSelection:=False) Assert.Equal("Imports System" + vbCrLf, testData.Buffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDontCrashOnPastingCarriageReturnContainingString() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Module Module1 Sub Main() $$ End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("f'x" + vbCr + """") testData.EditorOperations.MoveLineDown(extendSelection:=False) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539305")> Public Sub TestCommitAfterTypingAndUpArrowInLambdaFooter() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() Dim q = Sub() End$$ sub End Function End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("End Sub", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(5).GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539469")> Public Sub TestCommitAfterTypingAndUpArrowInLambdaFooter2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() Dim q = Sub() $$End Sub End Function End Module </Document> </Project> </Workspace>) Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) ' The text should snap back to what it originally was Dim originalText = initialTextSnapshot.GetLineFromLineNumber(5).GetText() Assert.Equal(originalText, testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(5).GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539457")> Public Sub TestCommitAfterTypingAndUpArrowIntoBlankLine() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() $$ End Function End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("dim x=42") testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("Dim x = 42", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(4).GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539411")> Public Sub TestCommitAfterTypingInTrivia() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M End Module $$</Document> </Project> </Workspace>) testData.EditorOperations.InsertText("#const goo=2.0d") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("#Const goo = 2D", testData.Buffer.CurrentSnapshot.Lines.Last().GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539599")> <WorkItem(631913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631913")> Public Sub TestCommitAfterTypingInTrivia2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M[| dim goo = 1 + _ _$$ 3|] End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal(" Dim goo = 1 + _", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(2).GetText()) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingAttributeOfType() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>[| $$|] Class Goo End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("<ComClass>") testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingAttributeOfMethod() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo[| $$|] Sub Bar() End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("<ClsCompliant>") testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingInMethodNameAndThenMovingToAttribute() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Goo[| <ClsCompilant> Sub $$Bar() End Sub|] End Class ]]></Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Goo") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestNoCommitDuringInlineRename() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Goo[| <ClsCompilant> Sub $$Bar() End Sub|] End Class ]]></Document> </Project> </Workspace>) testData.StartInlineRenameSession() testData.EditorOperations.InsertText("Goo") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(False) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539599")> Public Sub TestCommitAfterLeavingStatementAfterLineContinuation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim f3 = Function()[| Return $$Function(x As String) As String Return "" End Function|] End Function End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("_") testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine(), TestCommandExecutionContext.Create()) ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539318")> Public Sub TestCommitAfterDeletingIndentationFixesIndentation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| $$If True And False Then End If|] End Sub End Module </Document> </Project> </Workspace>) Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Assert.Equal(initialTextSnapshot.GetText(), testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitIfThenOnlyAfterStartingNewBlock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| $$|] If True Then End If End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("If True Then") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitEndIfOnlyAfterStartingNewBlock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main() If True Then End If[| $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End If") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitFullIfBlockAfterCommittingElseIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| If True Then Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("ElseIf False Then") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitFullIfBlockAfterCommittingEndIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| If True Then Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End If") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitTryBlockAfterCommittingCatch() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Try Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Catch") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitTryBlockAfterCommittingFinally() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Try Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Finally") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitDoLoopBlockAfterCommittingLoop() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Do Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Loop") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitEnumBlockAfterCommittingEndEnum() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace Program[| Enum Goo Alpha Bravo Charlie $$|] End Namespace </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End Enum") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitGetAccessorBlockAfterCommittingEndGet() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Public Property Bar As Integer[| Get $$|] End Property End Namespace </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End Get") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitSyncLockBlockAfterCommittingEndSyncLock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Goo()[| SyncLock Me Dim x = 42 $$|] End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End SyncLock") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539613")> Public Sub TestRelativeIndentationBug() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Dim a = Sub() Const x = 2 If True Then Console.WriteLine(x$$) End If Dim b = Sub() Console.WriteLine() End Sub End Function Sub Main() End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Dim expected = <Code> Module Module1 Dim a = Sub() Const x = 2 If True Then Console.WriteLine() End If Dim b = Sub() Console.WriteLine() End Sub End Function Sub Main() End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(16493, "DevDiv_Projects/Roslyn")> <WorkItem(539544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539544")> <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestBetterStartIndentation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If 1 = 1 Then Else : If 1 = 1 Then $$Else : If 1 = 1 Then End If End If End If End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Dim expected = <Code> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If 1 = 1 Then Else : If 1 = 1 Then Else : If 1 = 1 Then End If End If End If End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(544104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544104")> Public Sub TestCommitAfterMoveDownAfterIfStatement() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub Main() If True$$ End Sub End Class</Document> </Project> </Workspace>) Dim expected = <Code> Class C Sub Main() If True Then End Sub End Class</Code> testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineDown(extendSelection:=False) ' The text should snap back to what it originally was Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitAfterXmlElementStartTag() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Class C Dim x = &lt;code &gt;$$ &lt;/code&gt; End Class</Document> </Project> </Workspace>) Dim expected = <Code>Class C Dim x = &lt;code &gt; &lt;/code&gt; End Class</Code> testData.EditorOperations.InsertNewLine() Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <WorkItem(545358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545358")> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitWithNextStatementWithMultipleControlVariables() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Module Program Sub S() For a = 1 To 3 For b = 1 To 3 For c = 1 To 3 Next$$ Next b, a End Sub End Module</Document> </Project> </Workspace>) Dim expected = <Code>Module Program Sub S() For a = 1 To 3 For b = 1 To 3 For c = 1 To 3 Next Next b, a End Sub End Module</Code> testData.EditorOperations.InsertNewLine() Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <WorkItem(608438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608438")> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestBugfix_608438() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>[|$$Imports System Imports System.Linq Module Program Sub Main(args As String()) End Sub End Module|]</Document> </Project> </Workspace>) Dim document = testData.Workspace.Documents.Single() Dim onlyTextSpan = document.SelectedSpans.First() Dim snapshotspan = New SnapshotSpan(testData.Buffer.CurrentSnapshot, New Span(onlyTextSpan.Start, onlyTextSpan.Length)) Dim view = document.GetTextView() view.Selection.Select(snapshotspan, isReversed:=False) Dim selArgs = New FormatSelectionCommandArgs(view, document.GetTextBuffer()) testData.CommandHandler.ExecuteCommand(selArgs, Sub() Return, TestCommandExecutionContext.Create()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim s = "$$" End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M() Dim s = " " End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(s As String) M($$"") End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M(s As String) M( "") End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString3() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(s As String) M(""$$) End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M(s As String) M("" ) End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestEnableWarningDirective1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> # enable warning bc123,[bc456],BC789 ' Comment$$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> #Enable Warning bc123, [bc456], BC789 ' Comment </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestEnableWarningDirective2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> # enable warning $$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> #Enable Warning </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDisableWarningDirective1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main() #disable warning bc123, [bc456] _$$, someOtherId End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module Program Sub Main() #Disable Warning bc123, [bc456] _ , someOtherId End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDisableWarningDirective2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M1 # disable warning $$ 'Comment End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module M1 #Disable Warning 'Comment End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestIncompleteWarningDirective() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M1 # enable warning[BC123] , $$ End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module M1 #Enable Warning [BC123], End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(3119, "https://github.com/dotnet/roslyn/issues/3119")> <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestMissingThenInIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() If True $$ M() End If End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Class C Sub M() If True Then M() End If End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(3119, "https://github.com/dotnet/roslyn/issues/3119")> <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestMissingThenInElseIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() If True Then M() ElseIf False $$ M() End If End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Class C Sub M() If True Then M() ElseIf False Then M() End If End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit <[UseExportProvider]> Public Class CommitWithViewTests <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitAfterTypingAndDownArrow() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>imports $$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("System") testData.EditorOperations.MoveLineDown(extendSelection:=False) Assert.Equal("Imports System" + vbCrLf, testData.Buffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDontCrashOnPastingCarriageReturnContainingString() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Module Module1 Sub Main() $$ End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("f'x" + vbCr + """") testData.EditorOperations.MoveLineDown(extendSelection:=False) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539305")> Public Sub TestCommitAfterTypingAndUpArrowInLambdaFooter() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() Dim q = Sub() End$$ sub End Function End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("End Sub", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(5).GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539469")> Public Sub TestCommitAfterTypingAndUpArrowInLambdaFooter2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() Dim q = Sub() $$End Sub End Function End Module </Document> </Project> </Workspace>) Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) ' The text should snap back to what it originally was Dim originalText = initialTextSnapshot.GetLineFromLineNumber(5).GetText() Assert.Equal(originalText, testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(5).GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539457")> Public Sub TestCommitAfterTypingAndUpArrowIntoBlankLine() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Function Main() $$ End Function End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("dim x=42") testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("Dim x = 42", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(4).GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539411")> Public Sub TestCommitAfterTypingInTrivia() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M End Module $$</Document> </Project> </Workspace>) testData.EditorOperations.InsertText("#const goo=2.0d") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal("#Const goo = 2D", testData.Buffer.CurrentSnapshot.Lines.Last().GetText().Trim()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539599")> <WorkItem(631913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631913")> Public Sub TestCommitAfterTypingInTrivia2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M[| dim goo = 1 + _ _$$ 3|] End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.EditorOperations.MoveLineUp(extendSelection:=False) Assert.Equal(" Dim goo = 1 + _", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(2).GetText()) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingAttributeOfType() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>[| $$|] Class Goo End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("<ComClass>") testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingAttributeOfMethod() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo[| $$|] Sub Bar() End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("<ClsCompliant>") testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(545355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545355")> Public Sub TestCommitAfterTypingInMethodNameAndThenMovingToAttribute() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Goo[| <ClsCompilant> Sub $$Bar() End Sub|] End Class ]]></Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Goo") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestNoCommitDuringInlineRename() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Goo[| <ClsCompilant> Sub $$Bar() End Sub|] End Class ]]></Document> </Project> </Workspace>) testData.StartInlineRenameSession() testData.EditorOperations.InsertText("Goo") testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(False) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539599")> Public Sub TestCommitAfterLeavingStatementAfterLineContinuation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim f3 = Function()[| Return $$Function(x As String) As String Return "" End Function|] End Function End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("_") testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine(), TestCommandExecutionContext.Create()) ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineDown(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539318")> Public Sub TestCommitAfterDeletingIndentationFixesIndentation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| $$If True And False Then End If|] End Sub End Module </Document> </Project> </Workspace>) Dim initialTextSnapshot = testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Assert.Equal(initialTextSnapshot.GetText(), testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitIfThenOnlyAfterStartingNewBlock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| $$|] If True Then End If End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("If True Then") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitEndIfOnlyAfterStartingNewBlock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main() If True Then End If[| $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End If") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitFullIfBlockAfterCommittingElseIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| If True Then Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("ElseIf False Then") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitFullIfBlockAfterCommittingEndIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| If True Then Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End If") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitTryBlockAfterCommittingCatch() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Try Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Catch") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitTryBlockAfterCommittingFinally() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Try Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Finally") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitDoLoopBlockAfterCommittingLoop() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main()[| Do Dim x = 42 $$|] End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("Loop") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitEnumBlockAfterCommittingEndEnum() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace Program[| Enum Goo Alpha Bravo Charlie $$|] End Namespace </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End Enum") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitGetAccessorBlockAfterCommittingEndGet() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Public Property Bar As Integer[| Get $$|] End Property End Namespace </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End Get") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitSyncLockBlockAfterCommittingEndSyncLock() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Goo()[| SyncLock Me Dim x = 42 $$|] End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertText("End SyncLock") testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(539613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539613")> Public Sub TestRelativeIndentationBug() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Dim a = Sub() Const x = 2 If True Then Console.WriteLine(x$$) End If Dim b = Sub() Console.WriteLine() End Sub End Function Sub Main() End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Dim expected = <Code> Module Module1 Dim a = Sub() Const x = 2 If True Then Console.WriteLine() End If Dim b = Sub() Console.WriteLine() End Sub End Function Sub Main() End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(16493, "DevDiv_Projects/Roslyn")> <WorkItem(539544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539544")> <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestBetterStartIndentation() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If 1 = 1 Then Else : If 1 = 1 Then $$Else : If 1 = 1 Then End If End If End If End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.Backspace() testData.EditorOperations.Backspace() ' So far we should have had no commit testData.AssertHadCommit(False) testData.EditorOperations.MoveLineUp(extendSelection:=False) testData.AssertHadCommit(True) Dim expected = <Code> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If 1 = 1 Then Else : If 1 = 1 Then Else : If 1 = 1 Then End If End If End If End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(544104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544104")> Public Sub TestCommitAfterMoveDownAfterIfStatement() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub Main() If True$$ End Sub End Class</Document> </Project> </Workspace>) Dim expected = <Code> Class C Sub Main() If True Then End Sub End Class</Code> testData.EditorOperations.InsertText(" ") testData.EditorOperations.MoveLineDown(extendSelection:=False) ' The text should snap back to what it originally was Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitAfterXmlElementStartTag() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Class C Dim x = &lt;code &gt;$$ &lt;/code&gt; End Class</Document> </Project> </Workspace>) Dim expected = <Code>Class C Dim x = &lt;code &gt; &lt;/code&gt; End Class</Code> testData.EditorOperations.InsertNewLine() Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <WorkItem(545358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545358")> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestCommitWithNextStatementWithMultipleControlVariables() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>Module Program Sub S() For a = 1 To 3 For b = 1 To 3 For c = 1 To 3 Next$$ Next b, a End Sub End Module</Document> </Project> </Workspace>) Dim expected = <Code>Module Program Sub S() For a = 1 To 3 For b = 1 To 3 For c = 1 To 3 Next Next b, a End Sub End Module</Code> testData.EditorOperations.InsertNewLine() Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <WorkItem(608438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608438")> <Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestBugfix_608438() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>[|$$Imports System Imports System.Linq Module Program Sub Main(args As String()) End Sub End Module|]</Document> </Project> </Workspace>) Dim document = testData.Workspace.Documents.Single() Dim onlyTextSpan = document.SelectedSpans.First() Dim snapshotspan = New SnapshotSpan(testData.Buffer.CurrentSnapshot, New Span(onlyTextSpan.Start, onlyTextSpan.Length)) Dim view = document.GetTextView() view.Selection.Select(snapshotspan, isReversed:=False) Dim selArgs = New FormatSelectionCommandArgs(view, document.GetTextBuffer()) testData.CommandHandler.ExecuteCommand(selArgs, Sub() Return, TestCommandExecutionContext.Create()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim s = "$$" End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M() Dim s = " " End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(s As String) M($$"") End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M(s As String) M( "") End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.LineCommit)> <WorkItem(924578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924578")> Public Sub TestMultiLineString3() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(s As String) M(""$$) End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() Dim expected = <Code> Class C Sub M(s As String) M("" ) End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestEnableWarningDirective1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> # enable warning bc123,[bc456],BC789 ' Comment$$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> #Enable Warning bc123, [bc456], BC789 ' Comment </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestEnableWarningDirective2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> # enable warning $$ </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> #Enable Warning </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDisableWarningDirective1() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main() #disable warning bc123, [bc456] _$$, someOtherId End Sub End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module Program Sub Main() #Disable Warning bc123, [bc456] _ , someOtherId End Sub End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestDisableWarningDirective2() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M1 # disable warning $$ 'Comment End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module M1 #Disable Warning 'Comment End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestIncompleteWarningDirective() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M1 # enable warning[BC123] , $$ End Module </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Module M1 #Enable Warning [BC123], End Module </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(3119, "https://github.com/dotnet/roslyn/issues/3119")> <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestMissingThenInIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() If True $$ M() End If End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Class C Sub M() If True Then M() End If End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub <WorkItem(3119, "https://github.com/dotnet/roslyn/issues/3119")> <WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)> Public Sub TestMissingThenInElseIf() Using testData = CommitTestData.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() If True Then M() ElseIf False $$ M() End If End Sub End Class </Document> </Project> </Workspace>) testData.EditorOperations.InsertNewLine() testData.EditorOperations.MoveLineDown(False) Dim expected = <Code> Class C Sub M() If True Then M() ElseIf False Then M() End If End Sub End Class </Code> Assert.Equal(expected.NormalizedValue, testData.Workspace.Documents.Single().GetTextBuffer().CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/VisualStudio/Core/Def/Implementation/Utilities/ComEventSink.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class ComEventSink { public static ComEventSink Advise<T>(object obj, T sink) where T : class { if (!typeof(T).IsInterface) { throw new InvalidOperationException(); } if (!(obj is IConnectionPointContainer connectionPointContainer)) { throw new ArgumentException("Not an IConnectionPointContainer", nameof(obj)); } connectionPointContainer.FindConnectionPoint(typeof(T).GUID, out var connectionPoint); if (connectionPoint == null) { throw new InvalidOperationException("Could not find connection point for " + typeof(T).FullName); } connectionPoint.Advise(sink, out var cookie); return new ComEventSink(connectionPoint, cookie); } private readonly IConnectionPoint _connectionPoint; private readonly uint _cookie; private bool _unadvised; public ComEventSink(IConnectionPoint connectionPoint, uint cookie) { _connectionPoint = connectionPoint; _cookie = cookie; } public void Unadvise() { if (_unadvised) { throw new InvalidOperationException("Already unadvised."); } _connectionPoint.Unadvise(_cookie); _unadvised = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class ComEventSink { public static ComEventSink Advise<T>(object obj, T sink) where T : class { if (!typeof(T).IsInterface) { throw new InvalidOperationException(); } if (!(obj is IConnectionPointContainer connectionPointContainer)) { throw new ArgumentException("Not an IConnectionPointContainer", nameof(obj)); } connectionPointContainer.FindConnectionPoint(typeof(T).GUID, out var connectionPoint); if (connectionPoint == null) { throw new InvalidOperationException("Could not find connection point for " + typeof(T).FullName); } connectionPoint.Advise(sink, out var cookie); return new ComEventSink(connectionPoint, cookie); } private readonly IConnectionPoint _connectionPoint; private readonly uint _cookie; private bool _unadvised; public ComEventSink(IConnectionPoint connectionPoint, uint cookie) { _connectionPoint = connectionPoint; _cookie = cookie; } public void Unadvise() { if (_unadvised) { throw new InvalidOperationException("Already unadvised."); } _connectionPoint.Unadvise(_cookie); _unadvised = true; } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Core/Portable/PEWriter/Types.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Symbols; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal enum PlatformType { SystemObject = CodeAnalysis.SpecialType.System_Object, SystemDecimal = CodeAnalysis.SpecialType.System_Decimal, SystemTypedReference = CodeAnalysis.SpecialType.System_TypedReference, SystemType = CodeAnalysis.WellKnownType.System_Type, SystemInt32 = CodeAnalysis.SpecialType.System_Int32, SystemVoid = CodeAnalysis.SpecialType.System_Void, SystemString = CodeAnalysis.SpecialType.System_String, } /// <summary> /// This interface models the metadata representation of an array type reference. /// </summary> internal interface IArrayTypeReference : ITypeReference { /// <summary> /// The type of the elements of this array. /// </summary> ITypeReference GetElementType(EmitContext context); /// <summary> /// This type of array is a single dimensional array with zero lower bound for index values. /// </summary> bool IsSZArray { get; // ^ ensures result ==> Rank == 1; } /// <summary> /// A possibly empty list of lower bounds for dimension indices. When not explicitly specified, a lower bound defaults to zero. /// The first lower bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// </summary> ImmutableArray<int> LowerBounds { get; // ^ ensures count(result) <= Rank; } /// <summary> /// The number of array dimensions. /// </summary> int Rank { get; // ^ ensures result > 0; } /// <summary> /// A possible empty list of upper bounds for dimension indices. /// The first upper bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// An unspecified upper bound means that instances of this type can have an arbitrary upper bound for that dimension. /// </summary> ImmutableArray<int> Sizes { get; // ^ ensures count(result) <= Rank; } } /// <summary> /// Modifies the set of allowed values for a type, or the semantics of operations allowed on those values. /// Custom modifiers are not associated directly with types, but rather with typed storage locations for values. /// </summary> internal interface ICustomModifier { /// <summary> /// If true, a language may use the modified storage location without being aware of the meaning of the modification. /// </summary> bool IsOptional { get; } /// <summary> /// A type used as a tag that indicates which type of modification applies to the storage location. /// </summary> ITypeReference GetModifier(EmitContext context); } /// <summary> /// Information that describes a method or property parameter, but does not include all the information in a IParameterDefinition. /// </summary> internal interface IParameterTypeInformation : IParameterListEntry { /// <summary> /// The list of custom modifiers, if any, associated with the parameter type. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the ref modifier. /// </summary> ImmutableArray<ICustomModifier> RefCustomModifiers { get; } /// <summary> /// True if the parameter is passed by reference (using a managed pointer). /// </summary> bool IsByReference { get; } /// <summary> /// The type of argument value that corresponds to this parameter. /// </summary> ITypeReference GetType(EmitContext context); } /// <summary> /// The definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameter : IGenericParameterReference { /// <summary> /// A list of classes or interfaces. All type arguments matching this parameter must be derived from all of the classes and implement all of the interfaces. /// </summary> IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context); /// <summary> /// True if all type arguments matching this parameter are constrained to be reference types. /// </summary> bool MustBeReferenceType { get; // ^ ensures result ==> !this.MustBeValueType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types. /// </summary> bool MustBeValueType { get; // ^ ensures result ==> !this.MustBeReferenceType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types or concrete classes with visible default constructors. /// </summary> bool MustHaveDefaultConstructor { get; } /// <summary> /// Indicates if the generic type or method with this type parameter is co-, contra-, or non variant with respect to this type parameter. /// </summary> TypeParameterVariance Variance { get; } IGenericMethodParameter? AsGenericMethodParameter { get; } IGenericTypeParameter? AsGenericTypeParameter { get; } } /// <summary> /// A reference to the definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameterReference : ITypeReference, INamedEntity, IParameterListEntry { } /// <summary> /// The definition of a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameter : IGenericParameter, IGenericMethodParameterReference { /// <summary> /// The generic method that defines this type parameter. /// </summary> new IMethodDefinition DefiningMethod { get; // ^ ensures result.IsGeneric; } } /// <summary> /// A reference to a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic method that defines the referenced type parameter. /// </summary> IMethodReference DefiningMethod { get; } } /// <summary> /// A generic type instantiated with a list of type arguments /// </summary> internal interface IGenericTypeInstanceReference : ITypeReference { /// <summary> /// The type arguments that were used to instantiate this.GenericType in order to create this type. /// </summary> ImmutableArray<ITypeReference> GetGenericArguments(EmitContext context); // ^ ensures result.GetEnumerator().MoveNext(); // The collection is always non empty. /// <summary> /// Returns the generic type of which this type is an instance. /// Equivalent to Symbol.OriginalDefinition /// </summary> INamedTypeReference GetGenericType(EmitContext context); // ^ ensures result.ResolvedType.IsGeneric; } /// <summary> /// The definition of a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameter : IGenericParameter, IGenericTypeParameterReference { /// <summary> /// The generic type that defines this type parameter. /// </summary> new ITypeDefinition DefiningType { get; } } /// <summary> /// A reference to a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic type that defines the referenced type parameter. /// </summary> ITypeReference DefiningType { get; } } /// <summary> /// A reference to a named type, such as an INamespaceTypeReference or an INestedTypeReference. /// </summary> internal interface INamedTypeReference : ITypeReference, INamedEntity { /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { get; } /// <summary> /// If true, the persisted type name is mangled by appending "`n" where n is the number of type parameters, if the number of type parameters is greater than 0. /// </summary> bool MangleName { get; } } /// <summary> /// A named type definition, such as an INamespaceTypeDefinition or an INestedTypeDefinition. /// </summary> internal interface INamedTypeDefinition : ITypeDefinition, INamedTypeReference { } /// <summary> /// A type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeDefinition : INamedTypeDefinition, INamespaceTypeReference { /// <summary> /// True if the type can be accessed from other assemblies. /// </summary> bool IsPublic { get; } } /// <summary> /// Represents a namespace. /// </summary> internal interface INamespace : INamedEntity { /// <summary> /// Containing namespace or null if this namespace is global. /// </summary> INamespace ContainingNamespace { get; } /// <summary> /// Returns underlying internal symbol object, if any. /// </summary> INamespaceSymbolInternal GetInternalSymbol(); } /// <summary> /// A reference to a type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeReference : INamedTypeReference { /// <summary> /// A reference to the unit that defines the referenced type. /// </summary> IUnitReference GetUnit(EmitContext context); /// <summary> /// Fully qualified name of the containing namespace. /// </summary> string NamespaceName { get; } } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeDefinition : INamedTypeDefinition, ITypeDefinitionMember, INestedTypeReference { } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeReference : INamedTypeReference, ITypeMemberReference { } /// <summary> /// A reference to a type definition that is a specialized nested type. /// </summary> internal interface ISpecializedNestedTypeReference : INestedTypeReference { /// <summary> /// A reference to the nested type that has been specialized to obtain this nested type reference. When the containing type is an instance of type which is itself a specialized member (i.e. it is a nested /// type of a generic type instance), then the unspecialized member refers to a member from the unspecialized containing type. (I.e. the unspecialized member always /// corresponds to a definition that is not obtained via specialization.) /// </summary> [return: NotNull] INestedTypeReference GetUnspecializedVersion(EmitContext context); } /// <summary> /// Models an explicit implementation or override of a base class virtual method or an explicit implementation of an interface method. /// </summary> internal struct MethodImplementation { /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public readonly Cci.IMethodDefinition ImplementingMethod; /// <summary> /// A reference to the method that provides the implementation. /// </summary> public readonly Cci.IMethodReference ImplementedMethod; public MethodImplementation(Cci.IMethodDefinition ImplementingMethod, Cci.IMethodReference ImplementedMethod) { this.ImplementingMethod = ImplementingMethod; this.ImplementedMethod = ImplementedMethod; } /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public Cci.ITypeDefinition ContainingType { get { return ImplementingMethod.ContainingTypeDefinition; } } } /// <summary> /// A type reference that has custom modifiers associated with it. For example a reference to the target type of a managed pointer to a constant. /// </summary> internal interface IModifiedTypeReference : ITypeReference { /// <summary> /// Returns the list of custom modifiers associated with the type reference. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// An unmodified type reference. /// </summary> ITypeReference UnmodifiedType { get; } } /// <summary> /// This interface models the metadata representation of a pointer to a location in unmanaged memory. /// </summary> internal interface IPointerTypeReference : ITypeReference { /// <summary> /// The type of value stored at the target memory location. /// </summary> ITypeReference GetTargetType(EmitContext context); } /// <summary> /// This interface models the metadata representation of a pointer to a function in unmanaged memory. /// </summary> internal interface IFunctionPointerTypeReference : ITypeReference { /// <summary> /// The signature of the function located at the target memory address. /// </summary> ISignature Signature { get; } } /// <summary> /// A type ref with attributes attached directly to the type reference /// itself. Unlike <see cref="IReference.GetAttributes(EmitContext)"/> a /// <see cref="TypeReferenceWithAttributes"/> will never provide attributes /// for the "pointed at" declaration, and all attributes will be emitted /// directly on the type ref, rather than the declaration. /// </summary> // TODO(https://github.com/dotnet/roslyn/issues/12677): // Consider: This is basically just a work-around for our overly loose // interpretation of IReference and IDefinition. This type would probably // be unnecessary if we added a GetAttributes method onto IDefinition and // properly segregated attributes that are on type references and attributes // that are on underlying type definitions. internal struct TypeReferenceWithAttributes { /// <summary> /// The type reference. /// </summary> public ITypeReference TypeRef { get; } /// <summary> /// The attributes on the type reference itself. /// </summary> public ImmutableArray<ICustomAttribute> Attributes { get; } public TypeReferenceWithAttributes( ITypeReference typeRef, ImmutableArray<ICustomAttribute> attributes = default(ImmutableArray<ICustomAttribute>)) { TypeRef = typeRef; Attributes = attributes.NullToEmpty(); } } /// <summary> /// This interface models the metadata representation of a type. /// </summary> internal interface ITypeDefinition : IDefinition, ITypeReference { /// <summary> /// The byte alignment that values of the given type ought to have. Must be a power of 2. If zero, the alignment is decided at runtime. /// </summary> ushort Alignment { get; } /// <summary> /// Returns null for interfaces and System.Object. /// </summary> ITypeReference? GetBaseClass(EmitContext context); // ^ ensures result == null || result.ResolvedType.IsClass; /// <summary> /// Zero or more events defined by this type. /// </summary> IEnumerable<IEventDefinition> GetEvents(EmitContext context); /// <summary> /// Zero or more implementation overrides provided by the class. /// </summary> IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context); /// <summary> /// Zero or more fields defined by this type. /// </summary> IEnumerable<IFieldDefinition> GetFields(EmitContext context); /// <summary> /// Zero or more parameters that can be used as type annotations. /// </summary> IEnumerable<IGenericTypeParameter> GenericParameters { get; // ^ requires this.IsGeneric; } /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { // TODO: remove this get; // ^ ensures !this.IsGeneric ==> result == 0; // ^ ensures this.IsGeneric ==> result > 0; } /// <summary> /// True if this type has a non empty collection of SecurityAttributes or the System.Security.SuppressUnmanagedCodeSecurityAttribute. /// </summary> bool HasDeclarativeSecurity { get; } /// <summary> /// Zero or more interfaces implemented by this type. /// </summary> IEnumerable<TypeReferenceWithAttributes> Interfaces(EmitContext context); /// <summary> /// True if the type may not be instantiated. /// </summary> bool IsAbstract { get; } /// <summary> /// Is type initialized anytime before first access to static field /// </summary> bool IsBeforeFieldInit { get; } /// <summary> /// Is this imported from COM type library /// </summary> bool IsComObject { get; } /// <summary> /// True if this type is parameterized (this.GenericParameters is a non empty collection). /// </summary> bool IsGeneric { get; } /// <summary> /// True if the type is an interface. /// </summary> bool IsInterface { get; } /// <summary> /// True if the type is a delegate. /// </summary> bool IsDelegate { get; } /// <summary> /// True if this type gets special treatment from the runtime. /// </summary> bool IsRuntimeSpecial { get; } /// <summary> /// True if this type is serializable. /// </summary> bool IsSerializable { get; } /// <summary> /// True if the type has special name. /// </summary> bool IsSpecialName { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type may not be subtyped. /// </summary> bool IsSealed { get; } /// <summary> /// Layout of the type. /// </summary> LayoutKind Layout { get; } /// <summary> /// Zero or more methods defined by this type. /// </summary> IEnumerable<IMethodDefinition> GetMethods(EmitContext context); /// <summary> /// Zero or more nested types defined by this type. /// </summary> IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context); /// <summary> /// Zero or more properties defined by this type. /// </summary> IEnumerable<IPropertyDefinition> GetProperties(EmitContext context); /// <summary> /// Declarative security actions for this type. Will be empty if this.HasSecurity is false. /// </summary> IEnumerable<SecurityAttribute> SecurityAttributes { get; } /// <summary> /// Size of an object of this type. In bytes. If zero, the size is unspecified and will be determined at runtime. /// </summary> uint SizeOf { get; } /// <summary> /// Default marshalling of the Strings in this class. /// </summary> CharSet StringFormat { get; } } /// <summary> /// A reference to a type. /// </summary> internal interface ITypeReference : IReference { /// <summary> /// True if the type is an enumeration (it extends System.Enum and is sealed). Corresponds to C# enum. /// </summary> bool IsEnum { get; } /// <summary> /// True if the type is a value type. /// Value types are sealed and extend System.ValueType or System.Enum. /// A type parameter for which MustBeValueType (the struct constraint in C#) is true also returns true for this property. /// </summary> bool IsValueType { get; } /// <summary> /// The type definition being referred to. /// </summary> ITypeDefinition? GetResolvedType(EmitContext context); /// <summary> /// Unless the value of TypeCode is PrimitiveTypeCode.NotPrimitive, the type corresponds to a "primitive" CLR type (such as System.Int32) and /// the type code identifies which of the primitive types it corresponds to. /// </summary> PrimitiveTypeCode TypeCode { get; } /// <summary> /// TypeDefs defined in modules linked to the assembly being emitted are listed in the ExportedTypes table. /// </summary> TypeDefinitionHandle TypeDef { get; } IGenericMethodParameterReference? AsGenericMethodParameterReference { get; } IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get; } IGenericTypeParameterReference? AsGenericTypeParameterReference { get; } INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context); INamespaceTypeReference? AsNamespaceTypeReference { get; } INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context); INestedTypeReference? AsNestedTypeReference { get; } ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get; } ITypeDefinition? AsTypeDefinition(EmitContext context); } /// <summary> /// A enumeration of all of the value types that are built into the Runtime (and thus have specialized IL instructions that manipulate them). /// </summary> internal enum PrimitiveTypeCode { /// <summary> /// A single bit. /// </summary> Boolean, /// <summary> /// An unsigned 16 bit integer representing a Unicode UTF16 code point. /// </summary> Char, /// <summary> /// A signed 8 bit integer. /// </summary> Int8, /// <summary> /// A 32 bit IEEE floating point number. /// </summary> Float32, /// <summary> /// A 64 bit IEEE floating point number. /// </summary> Float64, /// <summary> /// A signed 16 bit integer. /// </summary> Int16, /// <summary> /// A signed 32 bit integer. /// </summary> Int32, /// <summary> /// A signed 64 bit integer. /// </summary> Int64, /// <summary> /// A signed 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> IntPtr, /// <summary> /// A pointer to fixed or unmanaged memory. /// </summary> Pointer, /// <summary> /// A reference to managed memory. /// </summary> Reference, /// <summary> /// A string. /// </summary> String, /// <summary> /// An unsigned 8 bit integer. /// </summary> UInt8, /// <summary> /// An unsigned 16 bit integer. /// </summary> UInt16, /// <summary> /// An unsigned 32 bit integer. /// </summary> UInt32, /// <summary> /// An unsigned 64 bit integer. /// </summary> UInt64, /// <summary> /// An unsigned 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> UIntPtr, /// <summary> /// A type that denotes the absence of a value. /// </summary> Void, /// <summary> /// Not a primitive type. /// </summary> NotPrimitive, /// <summary> /// A pointer to a function in fixed or managed memory. /// </summary> FunctionPointer, /// <summary> /// Type is a dummy type. /// </summary> Invalid, } /// <summary> /// Enumerates the different kinds of levels of visibility a type member can have. /// </summary> internal enum TypeMemberVisibility { /// <summary> /// The member is visible only within its own type. /// </summary> Private = 1, /// <summary> /// The member is visible only within the intersection of its family (its own type and any subtypes) and assembly. /// </summary> FamilyAndAssembly = 2, /// <summary> /// The member is visible only within its own assembly. /// </summary> Assembly = 3, /// <summary> /// The member is visible only within its own type and any subtypes. /// </summary> Family = 4, /// <summary> /// The member is visible only within the union of its family and assembly. /// </summary> FamilyOrAssembly = 5, /// <summary> /// The member is visible everywhere its declaring type is visible. /// </summary> Public = 6 } /// <summary> /// Enumerates the different kinds of variance a generic method or generic type parameter may have. /// </summary> internal enum TypeParameterVariance { /// <summary> /// Two type or method instances are compatible only if they have exactly the same type argument for this parameter. /// </summary> NonVariant = 0, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a subtype of the type the /// other instance has for this parameter. /// </summary> Covariant = 1, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a supertype of the type the /// other instance has for this parameter. /// </summary> Contravariant = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Symbols; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal enum PlatformType { SystemObject = CodeAnalysis.SpecialType.System_Object, SystemDecimal = CodeAnalysis.SpecialType.System_Decimal, SystemTypedReference = CodeAnalysis.SpecialType.System_TypedReference, SystemType = CodeAnalysis.WellKnownType.System_Type, SystemInt32 = CodeAnalysis.SpecialType.System_Int32, SystemVoid = CodeAnalysis.SpecialType.System_Void, SystemString = CodeAnalysis.SpecialType.System_String, } /// <summary> /// This interface models the metadata representation of an array type reference. /// </summary> internal interface IArrayTypeReference : ITypeReference { /// <summary> /// The type of the elements of this array. /// </summary> ITypeReference GetElementType(EmitContext context); /// <summary> /// This type of array is a single dimensional array with zero lower bound for index values. /// </summary> bool IsSZArray { get; // ^ ensures result ==> Rank == 1; } /// <summary> /// A possibly empty list of lower bounds for dimension indices. When not explicitly specified, a lower bound defaults to zero. /// The first lower bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// </summary> ImmutableArray<int> LowerBounds { get; // ^ ensures count(result) <= Rank; } /// <summary> /// The number of array dimensions. /// </summary> int Rank { get; // ^ ensures result > 0; } /// <summary> /// A possible empty list of upper bounds for dimension indices. /// The first upper bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// An unspecified upper bound means that instances of this type can have an arbitrary upper bound for that dimension. /// </summary> ImmutableArray<int> Sizes { get; // ^ ensures count(result) <= Rank; } } /// <summary> /// Modifies the set of allowed values for a type, or the semantics of operations allowed on those values. /// Custom modifiers are not associated directly with types, but rather with typed storage locations for values. /// </summary> internal interface ICustomModifier { /// <summary> /// If true, a language may use the modified storage location without being aware of the meaning of the modification. /// </summary> bool IsOptional { get; } /// <summary> /// A type used as a tag that indicates which type of modification applies to the storage location. /// </summary> ITypeReference GetModifier(EmitContext context); } /// <summary> /// Information that describes a method or property parameter, but does not include all the information in a IParameterDefinition. /// </summary> internal interface IParameterTypeInformation : IParameterListEntry { /// <summary> /// The list of custom modifiers, if any, associated with the parameter type. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the ref modifier. /// </summary> ImmutableArray<ICustomModifier> RefCustomModifiers { get; } /// <summary> /// True if the parameter is passed by reference (using a managed pointer). /// </summary> bool IsByReference { get; } /// <summary> /// The type of argument value that corresponds to this parameter. /// </summary> ITypeReference GetType(EmitContext context); } /// <summary> /// The definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameter : IGenericParameterReference { /// <summary> /// A list of classes or interfaces. All type arguments matching this parameter must be derived from all of the classes and implement all of the interfaces. /// </summary> IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context); /// <summary> /// True if all type arguments matching this parameter are constrained to be reference types. /// </summary> bool MustBeReferenceType { get; // ^ ensures result ==> !this.MustBeValueType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types. /// </summary> bool MustBeValueType { get; // ^ ensures result ==> !this.MustBeReferenceType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types or concrete classes with visible default constructors. /// </summary> bool MustHaveDefaultConstructor { get; } /// <summary> /// Indicates if the generic type or method with this type parameter is co-, contra-, or non variant with respect to this type parameter. /// </summary> TypeParameterVariance Variance { get; } IGenericMethodParameter? AsGenericMethodParameter { get; } IGenericTypeParameter? AsGenericTypeParameter { get; } } /// <summary> /// A reference to the definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameterReference : ITypeReference, INamedEntity, IParameterListEntry { } /// <summary> /// The definition of a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameter : IGenericParameter, IGenericMethodParameterReference { /// <summary> /// The generic method that defines this type parameter. /// </summary> new IMethodDefinition DefiningMethod { get; // ^ ensures result.IsGeneric; } } /// <summary> /// A reference to a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic method that defines the referenced type parameter. /// </summary> IMethodReference DefiningMethod { get; } } /// <summary> /// A generic type instantiated with a list of type arguments /// </summary> internal interface IGenericTypeInstanceReference : ITypeReference { /// <summary> /// The type arguments that were used to instantiate this.GenericType in order to create this type. /// </summary> ImmutableArray<ITypeReference> GetGenericArguments(EmitContext context); // ^ ensures result.GetEnumerator().MoveNext(); // The collection is always non empty. /// <summary> /// Returns the generic type of which this type is an instance. /// Equivalent to Symbol.OriginalDefinition /// </summary> INamedTypeReference GetGenericType(EmitContext context); // ^ ensures result.ResolvedType.IsGeneric; } /// <summary> /// The definition of a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameter : IGenericParameter, IGenericTypeParameterReference { /// <summary> /// The generic type that defines this type parameter. /// </summary> new ITypeDefinition DefiningType { get; } } /// <summary> /// A reference to a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic type that defines the referenced type parameter. /// </summary> ITypeReference DefiningType { get; } } /// <summary> /// A reference to a named type, such as an INamespaceTypeReference or an INestedTypeReference. /// </summary> internal interface INamedTypeReference : ITypeReference, INamedEntity { /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { get; } /// <summary> /// If true, the persisted type name is mangled by appending "`n" where n is the number of type parameters, if the number of type parameters is greater than 0. /// </summary> bool MangleName { get; } } /// <summary> /// A named type definition, such as an INamespaceTypeDefinition or an INestedTypeDefinition. /// </summary> internal interface INamedTypeDefinition : ITypeDefinition, INamedTypeReference { } /// <summary> /// A type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeDefinition : INamedTypeDefinition, INamespaceTypeReference { /// <summary> /// True if the type can be accessed from other assemblies. /// </summary> bool IsPublic { get; } } /// <summary> /// Represents a namespace. /// </summary> internal interface INamespace : INamedEntity { /// <summary> /// Containing namespace or null if this namespace is global. /// </summary> INamespace ContainingNamespace { get; } /// <summary> /// Returns underlying internal symbol object, if any. /// </summary> INamespaceSymbolInternal GetInternalSymbol(); } /// <summary> /// A reference to a type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeReference : INamedTypeReference { /// <summary> /// A reference to the unit that defines the referenced type. /// </summary> IUnitReference GetUnit(EmitContext context); /// <summary> /// Fully qualified name of the containing namespace. /// </summary> string NamespaceName { get; } } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeDefinition : INamedTypeDefinition, ITypeDefinitionMember, INestedTypeReference { } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeReference : INamedTypeReference, ITypeMemberReference { } /// <summary> /// A reference to a type definition that is a specialized nested type. /// </summary> internal interface ISpecializedNestedTypeReference : INestedTypeReference { /// <summary> /// A reference to the nested type that has been specialized to obtain this nested type reference. When the containing type is an instance of type which is itself a specialized member (i.e. it is a nested /// type of a generic type instance), then the unspecialized member refers to a member from the unspecialized containing type. (I.e. the unspecialized member always /// corresponds to a definition that is not obtained via specialization.) /// </summary> [return: NotNull] INestedTypeReference GetUnspecializedVersion(EmitContext context); } /// <summary> /// Models an explicit implementation or override of a base class virtual method or an explicit implementation of an interface method. /// </summary> internal struct MethodImplementation { /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public readonly Cci.IMethodDefinition ImplementingMethod; /// <summary> /// A reference to the method that provides the implementation. /// </summary> public readonly Cci.IMethodReference ImplementedMethod; public MethodImplementation(Cci.IMethodDefinition ImplementingMethod, Cci.IMethodReference ImplementedMethod) { this.ImplementingMethod = ImplementingMethod; this.ImplementedMethod = ImplementedMethod; } /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public Cci.ITypeDefinition ContainingType { get { return ImplementingMethod.ContainingTypeDefinition; } } } /// <summary> /// A type reference that has custom modifiers associated with it. For example a reference to the target type of a managed pointer to a constant. /// </summary> internal interface IModifiedTypeReference : ITypeReference { /// <summary> /// Returns the list of custom modifiers associated with the type reference. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// An unmodified type reference. /// </summary> ITypeReference UnmodifiedType { get; } } /// <summary> /// This interface models the metadata representation of a pointer to a location in unmanaged memory. /// </summary> internal interface IPointerTypeReference : ITypeReference { /// <summary> /// The type of value stored at the target memory location. /// </summary> ITypeReference GetTargetType(EmitContext context); } /// <summary> /// This interface models the metadata representation of a pointer to a function in unmanaged memory. /// </summary> internal interface IFunctionPointerTypeReference : ITypeReference { /// <summary> /// The signature of the function located at the target memory address. /// </summary> ISignature Signature { get; } } /// <summary> /// A type ref with attributes attached directly to the type reference /// itself. Unlike <see cref="IReference.GetAttributes(EmitContext)"/> a /// <see cref="TypeReferenceWithAttributes"/> will never provide attributes /// for the "pointed at" declaration, and all attributes will be emitted /// directly on the type ref, rather than the declaration. /// </summary> // TODO(https://github.com/dotnet/roslyn/issues/12677): // Consider: This is basically just a work-around for our overly loose // interpretation of IReference and IDefinition. This type would probably // be unnecessary if we added a GetAttributes method onto IDefinition and // properly segregated attributes that are on type references and attributes // that are on underlying type definitions. internal struct TypeReferenceWithAttributes { /// <summary> /// The type reference. /// </summary> public ITypeReference TypeRef { get; } /// <summary> /// The attributes on the type reference itself. /// </summary> public ImmutableArray<ICustomAttribute> Attributes { get; } public TypeReferenceWithAttributes( ITypeReference typeRef, ImmutableArray<ICustomAttribute> attributes = default(ImmutableArray<ICustomAttribute>)) { TypeRef = typeRef; Attributes = attributes.NullToEmpty(); } } /// <summary> /// This interface models the metadata representation of a type. /// </summary> internal interface ITypeDefinition : IDefinition, ITypeReference { /// <summary> /// The byte alignment that values of the given type ought to have. Must be a power of 2. If zero, the alignment is decided at runtime. /// </summary> ushort Alignment { get; } /// <summary> /// Returns null for interfaces and System.Object. /// </summary> ITypeReference? GetBaseClass(EmitContext context); // ^ ensures result == null || result.ResolvedType.IsClass; /// <summary> /// Zero or more events defined by this type. /// </summary> IEnumerable<IEventDefinition> GetEvents(EmitContext context); /// <summary> /// Zero or more implementation overrides provided by the class. /// </summary> IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context); /// <summary> /// Zero or more fields defined by this type. /// </summary> IEnumerable<IFieldDefinition> GetFields(EmitContext context); /// <summary> /// Zero or more parameters that can be used as type annotations. /// </summary> IEnumerable<IGenericTypeParameter> GenericParameters { get; // ^ requires this.IsGeneric; } /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { // TODO: remove this get; // ^ ensures !this.IsGeneric ==> result == 0; // ^ ensures this.IsGeneric ==> result > 0; } /// <summary> /// True if this type has a non empty collection of SecurityAttributes or the System.Security.SuppressUnmanagedCodeSecurityAttribute. /// </summary> bool HasDeclarativeSecurity { get; } /// <summary> /// Zero or more interfaces implemented by this type. /// </summary> IEnumerable<TypeReferenceWithAttributes> Interfaces(EmitContext context); /// <summary> /// True if the type may not be instantiated. /// </summary> bool IsAbstract { get; } /// <summary> /// Is type initialized anytime before first access to static field /// </summary> bool IsBeforeFieldInit { get; } /// <summary> /// Is this imported from COM type library /// </summary> bool IsComObject { get; } /// <summary> /// True if this type is parameterized (this.GenericParameters is a non empty collection). /// </summary> bool IsGeneric { get; } /// <summary> /// True if the type is an interface. /// </summary> bool IsInterface { get; } /// <summary> /// True if the type is a delegate. /// </summary> bool IsDelegate { get; } /// <summary> /// True if this type gets special treatment from the runtime. /// </summary> bool IsRuntimeSpecial { get; } /// <summary> /// True if this type is serializable. /// </summary> bool IsSerializable { get; } /// <summary> /// True if the type has special name. /// </summary> bool IsSpecialName { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type may not be subtyped. /// </summary> bool IsSealed { get; } /// <summary> /// Layout of the type. /// </summary> LayoutKind Layout { get; } /// <summary> /// Zero or more methods defined by this type. /// </summary> IEnumerable<IMethodDefinition> GetMethods(EmitContext context); /// <summary> /// Zero or more nested types defined by this type. /// </summary> IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context); /// <summary> /// Zero or more properties defined by this type. /// </summary> IEnumerable<IPropertyDefinition> GetProperties(EmitContext context); /// <summary> /// Declarative security actions for this type. Will be empty if this.HasSecurity is false. /// </summary> IEnumerable<SecurityAttribute> SecurityAttributes { get; } /// <summary> /// Size of an object of this type. In bytes. If zero, the size is unspecified and will be determined at runtime. /// </summary> uint SizeOf { get; } /// <summary> /// Default marshalling of the Strings in this class. /// </summary> CharSet StringFormat { get; } } /// <summary> /// A reference to a type. /// </summary> internal interface ITypeReference : IReference { /// <summary> /// True if the type is an enumeration (it extends System.Enum and is sealed). Corresponds to C# enum. /// </summary> bool IsEnum { get; } /// <summary> /// True if the type is a value type. /// Value types are sealed and extend System.ValueType or System.Enum. /// A type parameter for which MustBeValueType (the struct constraint in C#) is true also returns true for this property. /// </summary> bool IsValueType { get; } /// <summary> /// The type definition being referred to. /// </summary> ITypeDefinition? GetResolvedType(EmitContext context); /// <summary> /// Unless the value of TypeCode is PrimitiveTypeCode.NotPrimitive, the type corresponds to a "primitive" CLR type (such as System.Int32) and /// the type code identifies which of the primitive types it corresponds to. /// </summary> PrimitiveTypeCode TypeCode { get; } /// <summary> /// TypeDefs defined in modules linked to the assembly being emitted are listed in the ExportedTypes table. /// </summary> TypeDefinitionHandle TypeDef { get; } IGenericMethodParameterReference? AsGenericMethodParameterReference { get; } IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get; } IGenericTypeParameterReference? AsGenericTypeParameterReference { get; } INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context); INamespaceTypeReference? AsNamespaceTypeReference { get; } INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context); INestedTypeReference? AsNestedTypeReference { get; } ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get; } ITypeDefinition? AsTypeDefinition(EmitContext context); } /// <summary> /// A enumeration of all of the value types that are built into the Runtime (and thus have specialized IL instructions that manipulate them). /// </summary> internal enum PrimitiveTypeCode { /// <summary> /// A single bit. /// </summary> Boolean, /// <summary> /// An unsigned 16 bit integer representing a Unicode UTF16 code point. /// </summary> Char, /// <summary> /// A signed 8 bit integer. /// </summary> Int8, /// <summary> /// A 32 bit IEEE floating point number. /// </summary> Float32, /// <summary> /// A 64 bit IEEE floating point number. /// </summary> Float64, /// <summary> /// A signed 16 bit integer. /// </summary> Int16, /// <summary> /// A signed 32 bit integer. /// </summary> Int32, /// <summary> /// A signed 64 bit integer. /// </summary> Int64, /// <summary> /// A signed 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> IntPtr, /// <summary> /// A pointer to fixed or unmanaged memory. /// </summary> Pointer, /// <summary> /// A reference to managed memory. /// </summary> Reference, /// <summary> /// A string. /// </summary> String, /// <summary> /// An unsigned 8 bit integer. /// </summary> UInt8, /// <summary> /// An unsigned 16 bit integer. /// </summary> UInt16, /// <summary> /// An unsigned 32 bit integer. /// </summary> UInt32, /// <summary> /// An unsigned 64 bit integer. /// </summary> UInt64, /// <summary> /// An unsigned 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> UIntPtr, /// <summary> /// A type that denotes the absence of a value. /// </summary> Void, /// <summary> /// Not a primitive type. /// </summary> NotPrimitive, /// <summary> /// A pointer to a function in fixed or managed memory. /// </summary> FunctionPointer, /// <summary> /// Type is a dummy type. /// </summary> Invalid, } /// <summary> /// Enumerates the different kinds of levels of visibility a type member can have. /// </summary> internal enum TypeMemberVisibility { /// <summary> /// The member is visible only within its own type. /// </summary> Private = 1, /// <summary> /// The member is visible only within the intersection of its family (its own type and any subtypes) and assembly. /// </summary> FamilyAndAssembly = 2, /// <summary> /// The member is visible only within its own assembly. /// </summary> Assembly = 3, /// <summary> /// The member is visible only within its own type and any subtypes. /// </summary> Family = 4, /// <summary> /// The member is visible only within the union of its family and assembly. /// </summary> FamilyOrAssembly = 5, /// <summary> /// The member is visible everywhere its declaring type is visible. /// </summary> Public = 6 } /// <summary> /// Enumerates the different kinds of variance a generic method or generic type parameter may have. /// </summary> internal enum TypeParameterVariance { /// <summary> /// Two type or method instances are compatible only if they have exactly the same type argument for this parameter. /// </summary> NonVariant = 0, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a subtype of the type the /// other instance has for this parameter. /// </summary> Covariant = 1, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a supertype of the type the /// other instance has for this parameter. /// </summary> Contravariant = 2, } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/TryBlockHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class TryBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then Return End If Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)() If tryBlock Is Nothing Then Return End If With tryBlock highlights.Add(.TryStatement.TryKeyword.Span) HighlightRelatedStatements(tryBlock, highlights) For Each catchBlock In .CatchBlocks With catchBlock.CatchStatement highlights.Add(.CatchKeyword.Span) If .WhenClause IsNot Nothing Then highlights.Add(.WhenClause.WhenKeyword.Span) End If End With HighlightRelatedStatements(catchBlock, highlights) Next If .FinallyBlock IsNot Nothing Then highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span) End If highlights.Add(.EndTryStatement.Span) End With End Sub Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan)) If node.Kind = SyntaxKind.ExitTryStatement Then highlights.Add(node.Span) Else For Each childNodeOrToken In node.ChildNodesAndTokens() If childNodeOrToken.IsToken Then Continue For End If Dim child = childNodeOrToken.AsNode() If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then HighlightRelatedStatements(child, highlights) End If Next End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class TryBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then Return End If Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)() If tryBlock Is Nothing Then Return End If With tryBlock highlights.Add(.TryStatement.TryKeyword.Span) HighlightRelatedStatements(tryBlock, highlights) For Each catchBlock In .CatchBlocks With catchBlock.CatchStatement highlights.Add(.CatchKeyword.Span) If .WhenClause IsNot Nothing Then highlights.Add(.WhenClause.WhenKeyword.Span) End If End With HighlightRelatedStatements(catchBlock, highlights) Next If .FinallyBlock IsNot Nothing Then highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span) End If highlights.Add(.EndTryStatement.Span) End With End Sub Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan)) If node.Kind = SyntaxKind.ExitTryStatement Then highlights.Add(node.Span) Else For Each childNodeOrToken In node.ChildNodesAndTokens() If childNodeOrToken.IsToken Then Continue For End If Dim child = childNodeOrToken.AsNode() If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then HighlightRelatedStatements(child, highlights) End If Next End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/WithBlockTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class WithBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterWithStatement() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() With variable End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() With variable End With End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedWith() VerifyStatementEndConstructNotApplied( text:="Class c1 Sub goo() With variable End With End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedWith() VerifyStatementEndConstructApplied( before:="Class C Sub S With K With K End With End Sub End Class", beforeCaret:={3, -1}, after:="Class C Sub S With K With K End With End With End Sub End Class", afterCaret:={4, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyWithFollowsCode() VerifyStatementEndConstructApplied( before:="Class C Sub S With K Dim x = 5 End Sub End Class", beforeCaret:={2, -1}, after:="Class C Sub S With K End With Dim x = 5 End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S With using End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithLocation() VerifyStatementEndConstructNotApplied( text:="Class EC With True End Class", caret:={1, -1}) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class WithBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterWithStatement() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() With variable End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() With variable End With End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedWith() VerifyStatementEndConstructNotApplied( text:="Class c1 Sub goo() With variable End With End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedWith() VerifyStatementEndConstructApplied( before:="Class C Sub S With K With K End With End Sub End Class", beforeCaret:={3, -1}, after:="Class C Sub S With K With K End With End With End Sub End Class", afterCaret:={4, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyWithFollowsCode() VerifyStatementEndConstructApplied( before:="Class C Sub S With K Dim x = 5 End Sub End Class", beforeCaret:={2, -1}, after:="Class C Sub S With K End With Dim x = 5 End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S With using End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithLocation() VerifyStatementEndConstructNotApplied( text:="Class EC With True End Class", caret:={1, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Core/Portable/DiaSymReader/Utilities/IUnsafeComStream.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG; namespace Microsoft.DiaSymReader { /// <summary> /// This is a re-definition of COM's IStream interface. The important change is that /// the Read and Write methods take an <see cref="IntPtr"/> instead of a byte[] to avoid the /// allocation cost when called from native code. /// </summary> [Guid("0000000c-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport] internal unsafe interface IUnsafeComStream { // ISequentialStream portion void Read(byte* pv, int cb, int* pcbRead); void Write(byte* pv, int cb, int* pcbWritten); // IStream portion void Seek(long dlibMove, int dwOrigin, long* plibNewPosition); void SetSize(long libNewSize); void CopyTo(IStream pstm, long cb, int* pcbRead, int* pcbWritten); void Commit(int grfCommitFlags); void Revert(); void LockRegion(long libOffset, long cb, int dwLockType); void UnlockRegion(long libOffset, long cb, int dwLockType); void Stat(out STATSTG pstatstg, int grfStatFlag); void Clone(out IStream ppstm); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG; namespace Microsoft.DiaSymReader { /// <summary> /// This is a re-definition of COM's IStream interface. The important change is that /// the Read and Write methods take an <see cref="IntPtr"/> instead of a byte[] to avoid the /// allocation cost when called from native code. /// </summary> [Guid("0000000c-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport] internal unsafe interface IUnsafeComStream { // ISequentialStream portion void Read(byte* pv, int cb, int* pcbRead); void Write(byte* pv, int cb, int* pcbWritten); // IStream portion void Seek(long dlibMove, int dwOrigin, long* plibNewPosition); void SetSize(long libNewSize); void CopyTo(IStream pstm, long cb, int* pcbRead, int* pcbWritten); void Commit(int grfCommitFlags); void Revert(); void LockRegion(long libOffset, long cb, int dwLockType); void UnlockRegion(long libOffset, long cb, int dwLockType); void Stat(out STATSTG pstatstg, int grfStatFlag); void Clone(out IStream ppstm); } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./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
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { /// <summary> /// Analyzer that reports diagnostics in strings that we know are regex text. /// </summary> internal abstract class AbstractRegexDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public const string DiagnosticId = "RE0001"; private readonly EmbeddedLanguageInfo _info; protected AbstractRegexDiagnosticAnalyzer(EmbeddedLanguageInfo info) : base(DiagnosticId, EnforceOnBuildValues.Regex, RegularExpressionsOptions.ReportInvalidRegexPatterns, new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { _info = info; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSemanticModelAction(Analyze); public void Analyze(SemanticModelAnalysisContext context) { var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var option = context.GetOption(RegularExpressionsOptions.ReportInvalidRegexPatterns, syntaxTree.Options.Language); if (!option) { return; } var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); if (detector == null) { return; } // Use an actual stack object so that we don't blow the actual stack through recursion. var root = syntaxTree.GetRoot(cancellationToken); var stack = new Stack<SyntaxNode>(); stack.Push(root); while (stack.Count != 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { stack.Push(child.AsNode()); } else { AnalyzeToken(context, detector, child.AsToken(), cancellationToken); } } } } private void AnalyzeToken( SemanticModelAnalysisContext context, RegexPatternDetector detector, SyntaxToken token, CancellationToken cancellationToken) { if (token.RawKind == _info.StringLiteralTokenKind) { var tree = detector.TryParseRegexPattern(token, context.SemanticModel, cancellationToken); if (tree != null) { foreach (var diag in tree.Diagnostics) { context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, Location.Create(context.SemanticModel.SyntaxTree, diag.Span), ReportDiagnostic.Warn, additionalLocations: null, properties: null, diag.Message)); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { /// <summary> /// Analyzer that reports diagnostics in strings that we know are regex text. /// </summary> internal abstract class AbstractRegexDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public const string DiagnosticId = "RE0001"; private readonly EmbeddedLanguageInfo _info; protected AbstractRegexDiagnosticAnalyzer(EmbeddedLanguageInfo info) : base(DiagnosticId, EnforceOnBuildValues.Regex, RegularExpressionsOptions.ReportInvalidRegexPatterns, new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { _info = info; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSemanticModelAction(Analyze); public void Analyze(SemanticModelAnalysisContext context) { var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var option = context.GetOption(RegularExpressionsOptions.ReportInvalidRegexPatterns, syntaxTree.Options.Language); if (!option) { return; } var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); if (detector == null) { return; } // Use an actual stack object so that we don't blow the actual stack through recursion. var root = syntaxTree.GetRoot(cancellationToken); var stack = new Stack<SyntaxNode>(); stack.Push(root); while (stack.Count != 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { stack.Push(child.AsNode()); } else { AnalyzeToken(context, detector, child.AsToken(), cancellationToken); } } } } private void AnalyzeToken( SemanticModelAnalysisContext context, RegexPatternDetector detector, SyntaxToken token, CancellationToken cancellationToken) { if (token.RawKind == _info.StringLiteralTokenKind) { var tree = detector.TryParseRegexPattern(token, context.SemanticModel, cancellationToken); if (tree != null) { foreach (var diag in tree.Diagnostics) { context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, Location.Create(context.SemanticModel.SyntaxTree, diag.Span), ReportDiagnostic.Warn, additionalLocations: null, properties: null, diag.Message)); } } } } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Tools/ExternalAccess/FSharp/FSharpGlyphTags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { internal static class FSharpGlyphTags { public static ImmutableArray<string> GetTags(FSharpGlyph glyph) { return GlyphTags.GetTags(FSharpGlyphHelpers.ConvertTo(glyph)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { internal static class FSharpGlyphTags { public static ImmutableArray<string> GetTags(FSharpGlyph glyph) { return GlyphTags.GetTags(FSharpGlyphHelpers.ConvertTo(glyph)); } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/CSharpConvertForEachToLinqQueryProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery), Shared] internal sealed class CSharpConvertForEachToLinqQueryProvider : AbstractConvertForEachToLinqQueryProvider<ForEachStatementSyntax, StatementSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForEachToLinqQueryProvider() { } protected override IConverter<ForEachStatementSyntax, StatementSyntax> CreateDefaultConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => new DefaultConverter(forEachInfo); protected override ForEachInfo<ForEachStatementSyntax, StatementSyntax> CreateForEachInfo( ForEachStatementSyntax forEachStatement, SemanticModel semanticModel, bool convertLocalDeclarations) { var identifiersBuilder = ArrayBuilder<SyntaxToken>.GetInstance(); identifiersBuilder.Add(forEachStatement.Identifier); var convertingNodesBuilder = ArrayBuilder<ExtendedSyntaxNode>.GetInstance(); IEnumerable<StatementSyntax> statementsCannotBeConverted = null; var trailingTokensBuilder = ArrayBuilder<SyntaxToken>.GetInstance(); var currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); var current = forEachStatement.Statement; // Traverse descendants of the forEachStatement. // If a statement traversed can be converted into a query clause, // a. Add it to convertingNodesBuilder. // b. set the current to its nested statement and proceed. // Otherwise, set statementsCannotBeConverted and stop processing. while (statementsCannotBeConverted == null) { switch (current.Kind()) { case SyntaxKind.Block: var block = (BlockSyntax)current; // Keep comment trivia from braces to attach them to the qeury created. currentLeadingTokens.Add(block.OpenBraceToken); trailingTokensBuilder.Add(block.CloseBraceToken); var array = block.Statements.ToArray(); if (array.Length > 0) { // All except the last one can be local declaration statements like // { // var a = 0; // var b = 0; // if (x != y) <- this is the last one in the block. // We can support it to be a complex foreach or if or whatever. So, set the current to it. // ... // } for (var i = 0; i < array.Length - 1; i++) { var statement = array[i]; if (!(statement is LocalDeclarationStatementSyntax localDeclarationStatement && TryProcessLocalDeclarationStatement(localDeclarationStatement))) { // If this one is a local function declaration or has an empty initializer, stop processing. statementsCannotBeConverted = array.Skip(i).ToArray(); break; } } // Process the last statement separately. current = array.Last(); } else { // Silly case: the block is empty. Stop processing. statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); } break; case SyntaxKind.ForEachStatement: // foreach can always be converted to a from clause. var currentForEachStatement = (ForEachStatementSyntax)current; identifiersBuilder.Add(currentForEachStatement.Identifier); convertingNodesBuilder.Add(new ExtendedSyntaxNode(currentForEachStatement, currentLeadingTokens.ToImmutableAndFree(), Enumerable.Empty<SyntaxToken>())); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Proceed the loop with the nested statement. current = currentForEachStatement.Statement; break; case SyntaxKind.IfStatement: // Prepare conversion of 'if (condition)' into where clauses. // Do not support if-else statements in the conversion. var ifStatement = (IfStatementSyntax)current; if (ifStatement.Else == null) { convertingNodesBuilder.Add(new ExtendedSyntaxNode( ifStatement, currentLeadingTokens.ToImmutableAndFree(), Enumerable.Empty<SyntaxToken>())); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Proceed the loop with the nested statement. current = ifStatement.Statement; break; } else { statementsCannotBeConverted = new[] { current }; break; } case SyntaxKind.LocalDeclarationStatement: // This is a situation with "var a = something;" is the innermost statements inside the loop. var localDeclaration = (LocalDeclarationStatementSyntax)current; if (TryProcessLocalDeclarationStatement(localDeclaration)) { statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); } else { // As above, if there is an empty initializer, stop processing. statementsCannotBeConverted = new[] { current }; } break; case SyntaxKind.EmptyStatement: // The innermost statement is an empty statement, stop processing // Example: // foreach(...) // { // ;<- empty statement // } statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); break; default: // If no specific case found, stop processing. statementsCannotBeConverted = new[] { current }; break; } } // Trailing tokens are collected in the reverse order: from external block down to internal ones. Reverse them. trailingTokensBuilder.ReverseContents(); return new ForEachInfo<ForEachStatementSyntax, StatementSyntax>( forEachStatement, semanticModel, convertingNodesBuilder.ToImmutableAndFree(), identifiersBuilder.ToImmutableAndFree(), statementsCannotBeConverted.ToImmutableArray(), currentLeadingTokens.ToImmutableAndFree(), trailingTokensBuilder.ToImmutableAndFree()); // Try to prepare variable declarations to be converted into separate let clauses. bool TryProcessLocalDeclarationStatement(LocalDeclarationStatementSyntax localDeclarationStatement) { if (!convertLocalDeclarations) { return false; } // Do not support declarations without initialization. // int a = 0, b, c = 0; if (localDeclarationStatement.Declaration.Variables.All(variable => variable.Initializer != null)) { var localDeclarationLeadingTrivia = new IEnumerable<SyntaxTrivia>[] { currentLeadingTokens.ToImmutableAndFree().GetTrivia(), localDeclarationStatement.Declaration.Type.GetLeadingTrivia(), localDeclarationStatement.Declaration.Type.GetTrailingTrivia() }.Flatten(); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); var localDeclarationTrailingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(localDeclarationStatement.SemicolonToken); var separators = localDeclarationStatement.Declaration.Variables.GetSeparators().ToArray(); for (var i = 0; i < localDeclarationStatement.Declaration.Variables.Count; i++) { var variable = localDeclarationStatement.Declaration.Variables[i]; convertingNodesBuilder.Add(new ExtendedSyntaxNode( variable, i == 0 ? localDeclarationLeadingTrivia : separators[i - 1].TrailingTrivia, i == localDeclarationStatement.Declaration.Variables.Count - 1 ? (IEnumerable<SyntaxTrivia>)localDeclarationTrailingTrivia : separators[i].LeadingTrivia)); identifiersBuilder.Add(variable.Identifier); } return true; } return false; } } protected override bool TryBuildSpecificConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, SemanticModel semanticModel, StatementSyntax statementCannotBeConverted, CancellationToken cancellationToken, out IConverter<ForEachStatementSyntax, StatementSyntax> converter) { switch (statementCannotBeConverted.Kind()) { case SyntaxKind.ExpressionStatement: var expresisonStatement = (ExpressionStatementSyntax)statementCannotBeConverted; var expression = expresisonStatement.Expression; switch (expression.Kind()) { case SyntaxKind.PostIncrementExpression: // Input: // foreach (var x in a) // { // ... // c++; // } // Output: // (from x in a ... select x).Count(); // Here we put SyntaxFactory.IdentifierName(forEachStatement.Identifier) ('x' in the example) // into the select clause. var postfixUnaryExpression = (PostfixUnaryExpressionSyntax)expression; var operand = postfixUnaryExpression.Operand; converter = new ToCountConverter( forEachInfo, selectExpression: SyntaxFactory.IdentifierName(forEachInfo.ForEachStatement.Identifier), modifyingExpression: operand, trivia: SyntaxNodeOrTokenExtensions.GetTrivia( operand, postfixUnaryExpression.OperatorToken, expresisonStatement.SemicolonToken)); return true; case SyntaxKind.InvocationExpression: var invocationExpression = (InvocationExpressionSyntax)expression; // Check that there is 'list.Add(item)'. if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccessExpression && semanticModel.GetSymbolInfo(memberAccessExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol && TypeSymbolOptIsList(methodSymbol.ContainingType, semanticModel) && methodSymbol.Name == nameof(IList.Add) && methodSymbol.Parameters.Length == 1 && invocationExpression.ArgumentList.Arguments.Count == 1) { // Input: // foreach (var x in a) // { // ... // list.Add(...); // } // Output: // (from x in a ... select x).ToList(); var selectExpression = invocationExpression.ArgumentList.Arguments.Single().Expression; converter = new ToToListConverter( forEachInfo, selectExpression, modifyingExpression: memberAccessExpression.Expression, trivia: SyntaxNodeOrTokenExtensions.GetTrivia( memberAccessExpression, invocationExpression.ArgumentList.OpenParenToken, invocationExpression.ArgumentList.CloseParenToken, expresisonStatement.SemicolonToken)); return true; } break; } break; case SyntaxKind.YieldReturnStatement: var memberDeclarationSymbol = semanticModel.GetEnclosingSymbol( forEachInfo.ForEachStatement.SpanStart, cancellationToken); // Using Single() is valid even for partial methods. var memberDeclarationSyntax = memberDeclarationSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); var yieldStatementsCount = memberDeclarationSyntax.DescendantNodes().OfType<YieldStatementSyntax>() // Exclude yield statements from nested local functions. .Where(statement => Equals(semanticModel.GetEnclosingSymbol( statement.SpanStart, cancellationToken), memberDeclarationSymbol)).Count(); if (forEachInfo.ForEachStatement.IsParentKind(SyntaxKind.Block, out BlockSyntax block) && block.Parent == memberDeclarationSyntax) { // Check that // a. There are either just a single 'yield return' or 'yield return' with 'yield break' just after. // b. Those foreach and 'yield break' (if exists) are last statements in the method (do not count local function declaration statements). var statementsOnBlockWithForEach = block.Statements .Where(statement => statement.Kind() != SyntaxKind.LocalFunctionStatement).ToArray(); var lastNonLocalFunctionStatement = statementsOnBlockWithForEach.Last(); if (yieldStatementsCount == 1 && lastNonLocalFunctionStatement == forEachInfo.ForEachStatement) { converter = new YieldReturnConverter( forEachInfo, (YieldStatementSyntax)statementCannotBeConverted, yieldBreakStatement: null); return true; } // foreach() // { // yield return ...; // } // yield break; // end of member if (yieldStatementsCount == 2 && lastNonLocalFunctionStatement.Kind() == SyntaxKind.YieldBreakStatement && !lastNonLocalFunctionStatement.ContainsDirectives && statementsOnBlockWithForEach[statementsOnBlockWithForEach.Length - 2] == forEachInfo.ForEachStatement) { // This removes the yield break. converter = new YieldReturnConverter( forEachInfo, (YieldStatementSyntax)statementCannotBeConverted, yieldBreakStatement: (YieldStatementSyntax)lastNonLocalFunctionStatement); return true; } } break; } converter = null; return false; } protected override SyntaxNode AddLinqUsing( IConverter<ForEachStatementSyntax, StatementSyntax> converter, SemanticModel semanticModel, SyntaxNode root) { var namespaces = semanticModel.GetUsingNamespacesInScope(converter.ForEachInfo.ForEachStatement); if (!namespaces.Any(namespaceSymbol => namespaceSymbol.Name == nameof(System.Linq) && namespaceSymbol.ContainingNamespace.Name == nameof(System)) && root is CompilationUnitSyntax compilationUnit) { return compilationUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Linq"))); } return root; } internal static bool TypeSymbolOptIsList(ITypeSymbol typeSymbol, SemanticModel semanticModel) => Equals(typeSymbol?.OriginalDefinition, semanticModel.Compilation.GetTypeByMetadataName(typeof(List<>).FullName)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery), Shared] internal sealed class CSharpConvertForEachToLinqQueryProvider : AbstractConvertForEachToLinqQueryProvider<ForEachStatementSyntax, StatementSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForEachToLinqQueryProvider() { } protected override IConverter<ForEachStatementSyntax, StatementSyntax> CreateDefaultConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => new DefaultConverter(forEachInfo); protected override ForEachInfo<ForEachStatementSyntax, StatementSyntax> CreateForEachInfo( ForEachStatementSyntax forEachStatement, SemanticModel semanticModel, bool convertLocalDeclarations) { var identifiersBuilder = ArrayBuilder<SyntaxToken>.GetInstance(); identifiersBuilder.Add(forEachStatement.Identifier); var convertingNodesBuilder = ArrayBuilder<ExtendedSyntaxNode>.GetInstance(); IEnumerable<StatementSyntax> statementsCannotBeConverted = null; var trailingTokensBuilder = ArrayBuilder<SyntaxToken>.GetInstance(); var currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); var current = forEachStatement.Statement; // Traverse descendants of the forEachStatement. // If a statement traversed can be converted into a query clause, // a. Add it to convertingNodesBuilder. // b. set the current to its nested statement and proceed. // Otherwise, set statementsCannotBeConverted and stop processing. while (statementsCannotBeConverted == null) { switch (current.Kind()) { case SyntaxKind.Block: var block = (BlockSyntax)current; // Keep comment trivia from braces to attach them to the qeury created. currentLeadingTokens.Add(block.OpenBraceToken); trailingTokensBuilder.Add(block.CloseBraceToken); var array = block.Statements.ToArray(); if (array.Length > 0) { // All except the last one can be local declaration statements like // { // var a = 0; // var b = 0; // if (x != y) <- this is the last one in the block. // We can support it to be a complex foreach or if or whatever. So, set the current to it. // ... // } for (var i = 0; i < array.Length - 1; i++) { var statement = array[i]; if (!(statement is LocalDeclarationStatementSyntax localDeclarationStatement && TryProcessLocalDeclarationStatement(localDeclarationStatement))) { // If this one is a local function declaration or has an empty initializer, stop processing. statementsCannotBeConverted = array.Skip(i).ToArray(); break; } } // Process the last statement separately. current = array.Last(); } else { // Silly case: the block is empty. Stop processing. statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); } break; case SyntaxKind.ForEachStatement: // foreach can always be converted to a from clause. var currentForEachStatement = (ForEachStatementSyntax)current; identifiersBuilder.Add(currentForEachStatement.Identifier); convertingNodesBuilder.Add(new ExtendedSyntaxNode(currentForEachStatement, currentLeadingTokens.ToImmutableAndFree(), Enumerable.Empty<SyntaxToken>())); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Proceed the loop with the nested statement. current = currentForEachStatement.Statement; break; case SyntaxKind.IfStatement: // Prepare conversion of 'if (condition)' into where clauses. // Do not support if-else statements in the conversion. var ifStatement = (IfStatementSyntax)current; if (ifStatement.Else == null) { convertingNodesBuilder.Add(new ExtendedSyntaxNode( ifStatement, currentLeadingTokens.ToImmutableAndFree(), Enumerable.Empty<SyntaxToken>())); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Proceed the loop with the nested statement. current = ifStatement.Statement; break; } else { statementsCannotBeConverted = new[] { current }; break; } case SyntaxKind.LocalDeclarationStatement: // This is a situation with "var a = something;" is the innermost statements inside the loop. var localDeclaration = (LocalDeclarationStatementSyntax)current; if (TryProcessLocalDeclarationStatement(localDeclaration)) { statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); } else { // As above, if there is an empty initializer, stop processing. statementsCannotBeConverted = new[] { current }; } break; case SyntaxKind.EmptyStatement: // The innermost statement is an empty statement, stop processing // Example: // foreach(...) // { // ;<- empty statement // } statementsCannotBeConverted = Enumerable.Empty<StatementSyntax>(); break; default: // If no specific case found, stop processing. statementsCannotBeConverted = new[] { current }; break; } } // Trailing tokens are collected in the reverse order: from external block down to internal ones. Reverse them. trailingTokensBuilder.ReverseContents(); return new ForEachInfo<ForEachStatementSyntax, StatementSyntax>( forEachStatement, semanticModel, convertingNodesBuilder.ToImmutableAndFree(), identifiersBuilder.ToImmutableAndFree(), statementsCannotBeConverted.ToImmutableArray(), currentLeadingTokens.ToImmutableAndFree(), trailingTokensBuilder.ToImmutableAndFree()); // Try to prepare variable declarations to be converted into separate let clauses. bool TryProcessLocalDeclarationStatement(LocalDeclarationStatementSyntax localDeclarationStatement) { if (!convertLocalDeclarations) { return false; } // Do not support declarations without initialization. // int a = 0, b, c = 0; if (localDeclarationStatement.Declaration.Variables.All(variable => variable.Initializer != null)) { var localDeclarationLeadingTrivia = new IEnumerable<SyntaxTrivia>[] { currentLeadingTokens.ToImmutableAndFree().GetTrivia(), localDeclarationStatement.Declaration.Type.GetLeadingTrivia(), localDeclarationStatement.Declaration.Type.GetTrailingTrivia() }.Flatten(); currentLeadingTokens = ArrayBuilder<SyntaxToken>.GetInstance(); var localDeclarationTrailingTrivia = SyntaxNodeOrTokenExtensions.GetTrivia(localDeclarationStatement.SemicolonToken); var separators = localDeclarationStatement.Declaration.Variables.GetSeparators().ToArray(); for (var i = 0; i < localDeclarationStatement.Declaration.Variables.Count; i++) { var variable = localDeclarationStatement.Declaration.Variables[i]; convertingNodesBuilder.Add(new ExtendedSyntaxNode( variable, i == 0 ? localDeclarationLeadingTrivia : separators[i - 1].TrailingTrivia, i == localDeclarationStatement.Declaration.Variables.Count - 1 ? (IEnumerable<SyntaxTrivia>)localDeclarationTrailingTrivia : separators[i].LeadingTrivia)); identifiersBuilder.Add(variable.Identifier); } return true; } return false; } } protected override bool TryBuildSpecificConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, SemanticModel semanticModel, StatementSyntax statementCannotBeConverted, CancellationToken cancellationToken, out IConverter<ForEachStatementSyntax, StatementSyntax> converter) { switch (statementCannotBeConverted.Kind()) { case SyntaxKind.ExpressionStatement: var expresisonStatement = (ExpressionStatementSyntax)statementCannotBeConverted; var expression = expresisonStatement.Expression; switch (expression.Kind()) { case SyntaxKind.PostIncrementExpression: // Input: // foreach (var x in a) // { // ... // c++; // } // Output: // (from x in a ... select x).Count(); // Here we put SyntaxFactory.IdentifierName(forEachStatement.Identifier) ('x' in the example) // into the select clause. var postfixUnaryExpression = (PostfixUnaryExpressionSyntax)expression; var operand = postfixUnaryExpression.Operand; converter = new ToCountConverter( forEachInfo, selectExpression: SyntaxFactory.IdentifierName(forEachInfo.ForEachStatement.Identifier), modifyingExpression: operand, trivia: SyntaxNodeOrTokenExtensions.GetTrivia( operand, postfixUnaryExpression.OperatorToken, expresisonStatement.SemicolonToken)); return true; case SyntaxKind.InvocationExpression: var invocationExpression = (InvocationExpressionSyntax)expression; // Check that there is 'list.Add(item)'. if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccessExpression && semanticModel.GetSymbolInfo(memberAccessExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol && TypeSymbolOptIsList(methodSymbol.ContainingType, semanticModel) && methodSymbol.Name == nameof(IList.Add) && methodSymbol.Parameters.Length == 1 && invocationExpression.ArgumentList.Arguments.Count == 1) { // Input: // foreach (var x in a) // { // ... // list.Add(...); // } // Output: // (from x in a ... select x).ToList(); var selectExpression = invocationExpression.ArgumentList.Arguments.Single().Expression; converter = new ToToListConverter( forEachInfo, selectExpression, modifyingExpression: memberAccessExpression.Expression, trivia: SyntaxNodeOrTokenExtensions.GetTrivia( memberAccessExpression, invocationExpression.ArgumentList.OpenParenToken, invocationExpression.ArgumentList.CloseParenToken, expresisonStatement.SemicolonToken)); return true; } break; } break; case SyntaxKind.YieldReturnStatement: var memberDeclarationSymbol = semanticModel.GetEnclosingSymbol( forEachInfo.ForEachStatement.SpanStart, cancellationToken); // Using Single() is valid even for partial methods. var memberDeclarationSyntax = memberDeclarationSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); var yieldStatementsCount = memberDeclarationSyntax.DescendantNodes().OfType<YieldStatementSyntax>() // Exclude yield statements from nested local functions. .Where(statement => Equals(semanticModel.GetEnclosingSymbol( statement.SpanStart, cancellationToken), memberDeclarationSymbol)).Count(); if (forEachInfo.ForEachStatement.IsParentKind(SyntaxKind.Block, out BlockSyntax block) && block.Parent == memberDeclarationSyntax) { // Check that // a. There are either just a single 'yield return' or 'yield return' with 'yield break' just after. // b. Those foreach and 'yield break' (if exists) are last statements in the method (do not count local function declaration statements). var statementsOnBlockWithForEach = block.Statements .Where(statement => statement.Kind() != SyntaxKind.LocalFunctionStatement).ToArray(); var lastNonLocalFunctionStatement = statementsOnBlockWithForEach.Last(); if (yieldStatementsCount == 1 && lastNonLocalFunctionStatement == forEachInfo.ForEachStatement) { converter = new YieldReturnConverter( forEachInfo, (YieldStatementSyntax)statementCannotBeConverted, yieldBreakStatement: null); return true; } // foreach() // { // yield return ...; // } // yield break; // end of member if (yieldStatementsCount == 2 && lastNonLocalFunctionStatement.Kind() == SyntaxKind.YieldBreakStatement && !lastNonLocalFunctionStatement.ContainsDirectives && statementsOnBlockWithForEach[statementsOnBlockWithForEach.Length - 2] == forEachInfo.ForEachStatement) { // This removes the yield break. converter = new YieldReturnConverter( forEachInfo, (YieldStatementSyntax)statementCannotBeConverted, yieldBreakStatement: (YieldStatementSyntax)lastNonLocalFunctionStatement); return true; } } break; } converter = null; return false; } protected override SyntaxNode AddLinqUsing( IConverter<ForEachStatementSyntax, StatementSyntax> converter, SemanticModel semanticModel, SyntaxNode root) { var namespaces = semanticModel.GetUsingNamespacesInScope(converter.ForEachInfo.ForEachStatement); if (!namespaces.Any(namespaceSymbol => namespaceSymbol.Name == nameof(System.Linq) && namespaceSymbol.ContainingNamespace.Name == nameof(System)) && root is CompilationUnitSyntax compilationUnit) { return compilationUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Linq"))); } return root; } internal static bool TypeSymbolOptIsList(ITypeSymbol typeSymbol, SemanticModel semanticModel) => Equals(typeSymbol?.OriginalDefinition, semanticModel.Compilation.GetTypeByMetadataName(typeof(List<>).FullName)); } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/Core/Portable/FindUsages/DefinitionsAndReferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// A collection of <see cref="DefinitionItem"/>s and <see cref="SourceReferenceItem"/>s /// that can be presented in an editor and used to navigate to the defintions and /// references found for a symbol. /// </summary> internal readonly struct DefinitionsAndReferences { public static readonly DefinitionsAndReferences Empty = new(ImmutableArray<DefinitionItem>.Empty, ImmutableArray<SourceReferenceItem>.Empty); /// <summary> /// All the definitions to show. Note: not all definitions may have references. /// </summary> public ImmutableArray<DefinitionItem> Definitions { get; } /// <summary> /// All the references to show. Note: every <see cref="SourceReferenceItem.Definition"/> /// should be in <see cref="Definitions"/> /// </summary> public ImmutableArray<SourceReferenceItem> References { get; } public DefinitionsAndReferences( ImmutableArray<DefinitionItem> definitions, ImmutableArray<SourceReferenceItem> references) { var definitionSet = definitions.ToSet(); for (int i = 0, n = references.Length; i < n; i++) { var reference = references[i]; if (!definitionSet.Contains(reference.Definition)) { throw new ArgumentException( $"{nameof(references)}[{i}].{nameof(reference.Definition)} not found in '{nameof(definitions)}'"); } } Definitions = definitions; References = references; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// A collection of <see cref="DefinitionItem"/>s and <see cref="SourceReferenceItem"/>s /// that can be presented in an editor and used to navigate to the defintions and /// references found for a symbol. /// </summary> internal readonly struct DefinitionsAndReferences { public static readonly DefinitionsAndReferences Empty = new(ImmutableArray<DefinitionItem>.Empty, ImmutableArray<SourceReferenceItem>.Empty); /// <summary> /// All the definitions to show. Note: not all definitions may have references. /// </summary> public ImmutableArray<DefinitionItem> Definitions { get; } /// <summary> /// All the references to show. Note: every <see cref="SourceReferenceItem.Definition"/> /// should be in <see cref="Definitions"/> /// </summary> public ImmutableArray<SourceReferenceItem> References { get; } public DefinitionsAndReferences( ImmutableArray<DefinitionItem> definitions, ImmutableArray<SourceReferenceItem> references) { var definitionSet = definitions.ToSet(); for (int i = 0, n = references.Length; i < n; i++) { var reference = references[i]; if (!definitionSet.Contains(reference.Definition)) { throw new ArgumentException( $"{nameof(references)}[{i}].{nameof(reference.Definition)} not found in '{nameof(definitions)}'"); } } Definitions = definitions; References = references; } } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/Core/Portable/Operations/IConvertibleConversion.cs
// Licensed to the .NET Foundation under one or more 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.Operations { internal interface IConvertibleConversion { CommonConversion ToCommonConversion(); } }
// Licensed to the .NET Foundation under one or more 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.Operations { internal interface IConvertibleConversion { CommonConversion ToCommonConversion(); } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/BinaryExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { public class BinaryExpressionChanges { // This test is an exception to the others as * will be assumed to be a pointer type in an // expression syntax. To make this parse correctly, the multiplication must be in a location // that is definitely an expression (i.e. an assignment expression) [Fact] public void PlusToMultiply() { string text = @"class C{ void M() { int x = y + 2; } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = oldTree.WithReplaceFirst("+", "*"); var type = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = type.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as LocalDeclarationStatementSyntax; var expression = statement.Declaration.Variables[0].Initializer.Value as BinaryExpressionSyntax; Assert.Equal(SyntaxKind.MultiplyExpression, expression.Kind()); } [Fact] public void PlusToMinus() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.SubtractExpression); } [Fact] public void PlusToDivide() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.DivideExpression); } [Fact] public void PlusToModulo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.ModuloExpression); } [Fact] public void PlusToLeftShift() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LeftShiftExpression); } [Fact] public void PlusToRightShift() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.RightShiftExpression); } [Fact] public void PlusToLogicalOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LogicalOrExpression); } [Fact] public void PlusToLogicalAnd() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LogicalAndExpression); } [Fact] public void PlusToBitwiseAnd() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.BitwiseAndExpression); } [Fact] public void PlusToBitwiseOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.BitwiseOrExpression); } [Fact] public void PlusToExclusiveOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.ExclusiveOrExpression); } [Fact] public void PlusToEquals() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.EqualsExpression); } [Fact] public void PlusToNotEquals() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.NotEqualsExpression); } [Fact] public void PlusToLessThan() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LessThanExpression); } [Fact] public void PlusToLessThanEqualTo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LessThanOrEqualExpression); } [Fact] public void PlusToGreaterThan() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.GreaterThanExpression); } [Fact] public void PlusToGreaterThanEqualTo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.GreaterThanOrEqualExpression); } [Fact] public void PlusToAs() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.AsExpression); } [Fact] public void PlusToIs() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.IsExpression); } [Fact] public void PlusToCoalesce() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.CoalesceExpression); } [Fact] public void DotToArrow() { MakeMemberAccessChange(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.PointerMemberAccessExpression); } [Fact] public void ArrowToDot() { MakeMemberAccessChange(SyntaxKind.PointerMemberAccessExpression, SyntaxKind.SimpleMemberAccessExpression); } #region Helpers private static void MakeMemberAccessChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeChange(oldStyle, newStyle); MakeChange(oldStyle, newStyle, options: TestOptions.Script); MakeChange(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeBinOpChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeChange(oldStyle, newStyle); MakeChange(oldStyle, newStyle, options: TestOptions.Script); MakeChange(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeChange(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = "x " + oldName + " y"; // Be warned when changing the fields here var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var treeNode = topLevel ? GetGlobalExpressionNode(newTree) : GetExpressionNode(newTree); Assert.Equal(treeNode.Kind(), newSyntaxKind); } private static ExpressionSyntax GetExpressionNode(SyntaxTree newTree) { TypeDeclarationSyntax classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; MethodDeclarationSyntax method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; return statement.Expression; } private static ExpressionSyntax GetGlobalExpressionNode(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; return statement.Expression; } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.AddExpression: return "+"; case SyntaxKind.SubtractExpression: return "-"; case SyntaxKind.MultiplyExpression: return " * "; case SyntaxKind.DivideExpression: return "/"; case SyntaxKind.ModuloExpression: return "%"; case SyntaxKind.LeftShiftExpression: return "<<"; case SyntaxKind.RightShiftExpression: return ">>"; case SyntaxKind.LogicalOrExpression: return "||"; case SyntaxKind.LogicalAndExpression: return "&&"; case SyntaxKind.BitwiseOrExpression: return "|"; case SyntaxKind.BitwiseAndExpression: return "&"; case SyntaxKind.ExclusiveOrExpression: return "^"; case SyntaxKind.EqualsExpression: return "=="; case SyntaxKind.NotEqualsExpression: return "!="; case SyntaxKind.LessThanExpression: return "<"; case SyntaxKind.LessThanOrEqualExpression: return "<="; case SyntaxKind.GreaterThanExpression: return ">"; case SyntaxKind.GreaterThanOrEqualExpression: return ">="; case SyntaxKind.AsExpression: return " as "; case SyntaxKind.IsExpression: return " is "; case SyntaxKind.CoalesceExpression: return "??"; case SyntaxKind.SimpleMemberAccessExpression: return "."; case SyntaxKind.PointerMemberAccessExpression: return "->"; default: throw new Exception("unexpected Type given"); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { public class BinaryExpressionChanges { // This test is an exception to the others as * will be assumed to be a pointer type in an // expression syntax. To make this parse correctly, the multiplication must be in a location // that is definitely an expression (i.e. an assignment expression) [Fact] public void PlusToMultiply() { string text = @"class C{ void M() { int x = y + 2; } }"; var oldTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = oldTree.WithReplaceFirst("+", "*"); var type = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = type.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as LocalDeclarationStatementSyntax; var expression = statement.Declaration.Variables[0].Initializer.Value as BinaryExpressionSyntax; Assert.Equal(SyntaxKind.MultiplyExpression, expression.Kind()); } [Fact] public void PlusToMinus() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.SubtractExpression); } [Fact] public void PlusToDivide() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.DivideExpression); } [Fact] public void PlusToModulo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.ModuloExpression); } [Fact] public void PlusToLeftShift() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LeftShiftExpression); } [Fact] public void PlusToRightShift() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.RightShiftExpression); } [Fact] public void PlusToLogicalOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LogicalOrExpression); } [Fact] public void PlusToLogicalAnd() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LogicalAndExpression); } [Fact] public void PlusToBitwiseAnd() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.BitwiseAndExpression); } [Fact] public void PlusToBitwiseOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.BitwiseOrExpression); } [Fact] public void PlusToExclusiveOr() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.ExclusiveOrExpression); } [Fact] public void PlusToEquals() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.EqualsExpression); } [Fact] public void PlusToNotEquals() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.NotEqualsExpression); } [Fact] public void PlusToLessThan() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LessThanExpression); } [Fact] public void PlusToLessThanEqualTo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.LessThanOrEqualExpression); } [Fact] public void PlusToGreaterThan() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.GreaterThanExpression); } [Fact] public void PlusToGreaterThanEqualTo() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.GreaterThanOrEqualExpression); } [Fact] public void PlusToAs() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.AsExpression); } [Fact] public void PlusToIs() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.IsExpression); } [Fact] public void PlusToCoalesce() { MakeBinOpChange(SyntaxKind.AddExpression, SyntaxKind.CoalesceExpression); } [Fact] public void DotToArrow() { MakeMemberAccessChange(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.PointerMemberAccessExpression); } [Fact] public void ArrowToDot() { MakeMemberAccessChange(SyntaxKind.PointerMemberAccessExpression, SyntaxKind.SimpleMemberAccessExpression); } #region Helpers private static void MakeMemberAccessChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeChange(oldStyle, newStyle); MakeChange(oldStyle, newStyle, options: TestOptions.Script); MakeChange(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeBinOpChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeChange(oldStyle, newStyle); MakeChange(oldStyle, newStyle, options: TestOptions.Script); MakeChange(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeChange(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = "x " + oldName + " y"; // Be warned when changing the fields here var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var treeNode = topLevel ? GetGlobalExpressionNode(newTree) : GetExpressionNode(newTree); Assert.Equal(treeNode.Kind(), newSyntaxKind); } private static ExpressionSyntax GetExpressionNode(SyntaxTree newTree) { TypeDeclarationSyntax classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; MethodDeclarationSyntax method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; return statement.Expression; } private static ExpressionSyntax GetGlobalExpressionNode(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; return statement.Expression; } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.AddExpression: return "+"; case SyntaxKind.SubtractExpression: return "-"; case SyntaxKind.MultiplyExpression: return " * "; case SyntaxKind.DivideExpression: return "/"; case SyntaxKind.ModuloExpression: return "%"; case SyntaxKind.LeftShiftExpression: return "<<"; case SyntaxKind.RightShiftExpression: return ">>"; case SyntaxKind.LogicalOrExpression: return "||"; case SyntaxKind.LogicalAndExpression: return "&&"; case SyntaxKind.BitwiseOrExpression: return "|"; case SyntaxKind.BitwiseAndExpression: return "&"; case SyntaxKind.ExclusiveOrExpression: return "^"; case SyntaxKind.EqualsExpression: return "=="; case SyntaxKind.NotEqualsExpression: return "!="; case SyntaxKind.LessThanExpression: return "<"; case SyntaxKind.LessThanOrEqualExpression: return "<="; case SyntaxKind.GreaterThanExpression: return ">"; case SyntaxKind.GreaterThanOrEqualExpression: return ">="; case SyntaxKind.AsExpression: return " as "; case SyntaxKind.IsExpression: return " is "; case SyntaxKind.CoalesceExpression: return "??"; case SyntaxKind.SimpleMemberAccessExpression: return "."; case SyntaxKind.PointerMemberAccessExpression: return "->"; default: throw new Exception("unexpected Type given"); } } #endregion } }
-1
dotnet/roslyn
55,614
Move NonRemappableRegions, Capabilities to EditSession
Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
tmat
2021-08-13T18:46:58Z
2021-08-16T16:50:03Z
7fb7af26eafae33fa23ce72a16f42e694e3bc177
612b978e951f219b625f1b117d6d0f0f48a0ca55
Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession. Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed. Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements. Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/WithKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 WithKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public WithKeywordRecommender() : base(SyntaxKind.WithKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 WithKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public WithKeywordRecommender() : base(SyntaxKind.WithKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext; } }
-1