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:<n>=<v> 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:<n>=<v> 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:<n>=<v> 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:<n>=<v> 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:<n>=<v> 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:<n>=<v> 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.
$ PE L lM ! n/ @ @ @ / W @ ` H .text t `.rsrc @ @ @.reloc ` @ B P/ 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.30319 l 8 #~ #Strings
#US
#GUID
L #Blob W %3 & |