repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/Utilities/VisualStudioWaitContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [Obsolete] internal sealed partial class VisualStudioWaitContext : IWaitContext { private const int DelayToShowDialogSecs = 2; private readonly IVsThreadedWaitDialog3 _dialog; private readonly CancellationTokenSource _cancellationTokenSource; private readonly GlobalOperationRegistration _registration; private readonly string _title; private string _message; private bool _allowCancel; public IProgressTracker ProgressTracker { get; } public VisualStudioWaitContext( IGlobalOperationNotificationService notificationService, IVsThreadedWaitDialogFactory dialogFactory, string title, string message, bool allowCancel, bool showProgress) { _title = title; _message = message; _allowCancel = allowCancel; _cancellationTokenSource = new CancellationTokenSource(); this.ProgressTracker = showProgress ? new ProgressTracker((_1, _2, _3) => UpdateDialog()) : new ProgressTracker(); _dialog = CreateDialog(dialogFactory, showProgress); _registration = notificationService.Start(title); } private IVsThreadedWaitDialog3 CreateDialog( IVsThreadedWaitDialogFactory dialogFactory, bool showProgress) { Marshal.ThrowExceptionForHR(dialogFactory.CreateInstance(out var dialog2)); Contract.ThrowIfNull(dialog2); var dialog3 = (IVsThreadedWaitDialog3)dialog2; var callback = new Callback(this); dialog3.StartWaitDialogWithCallback( szWaitCaption: _title, szWaitMessage: this.ProgressTracker.Description ?? _message, szProgressText: null, varStatusBmpAnim: null, szStatusBarText: null, fIsCancelable: _allowCancel, iDelayToShowDialog: DelayToShowDialogSecs, fShowProgress: showProgress, iTotalSteps: this.ProgressTracker.TotalItems, iCurrentStep: this.ProgressTracker.CompletedItems, pCallback: callback); return dialog3; } public CancellationToken CancellationToken { get { return _allowCancel ? _cancellationTokenSource.Token : CancellationToken.None; } } public string Message { get { return _message; } set { _message = value; UpdateDialog(); } } public bool AllowCancel { get { return _allowCancel; } set { _allowCancel = value; UpdateDialog(); } } private void UpdateDialog() { ((IVsThreadedWaitDialog2)_dialog).UpdateProgress( this.ProgressTracker.Description ?? _message, szProgressText: null, szStatusBarText: null, iCurrentStep: this.ProgressTracker.CompletedItems, iTotalSteps: this.ProgressTracker.TotalItems, fDisableCancel: !_allowCancel, pfCanceled: out _); } public void Dispose() { _dialog.EndWaitDialog(out var canceled); // Let the global operation object know that we completed with/without user cancelling. If the user // canceled, we won't call 'Done', and so calling 'Dispose' will log that we didn't complete fully. if (canceled == 0) _registration.Done(); _registration.Dispose(); } private void OnCanceled() { if (_allowCancel) { _cancellationTokenSource.Cancel(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [Obsolete] internal sealed partial class VisualStudioWaitContext : IWaitContext { private const int DelayToShowDialogSecs = 2; private readonly IVsThreadedWaitDialog3 _dialog; private readonly CancellationTokenSource _cancellationTokenSource; private readonly GlobalOperationRegistration _registration; private readonly string _title; private string _message; private bool _allowCancel; public IProgressTracker ProgressTracker { get; } public VisualStudioWaitContext( IGlobalOperationNotificationService notificationService, IVsThreadedWaitDialogFactory dialogFactory, string title, string message, bool allowCancel, bool showProgress) { _title = title; _message = message; _allowCancel = allowCancel; _cancellationTokenSource = new CancellationTokenSource(); this.ProgressTracker = showProgress ? new ProgressTracker((_1, _2, _3) => UpdateDialog()) : new ProgressTracker(); _dialog = CreateDialog(dialogFactory, showProgress); _registration = notificationService.Start(title); } private IVsThreadedWaitDialog3 CreateDialog( IVsThreadedWaitDialogFactory dialogFactory, bool showProgress) { Marshal.ThrowExceptionForHR(dialogFactory.CreateInstance(out var dialog2)); Contract.ThrowIfNull(dialog2); var dialog3 = (IVsThreadedWaitDialog3)dialog2; var callback = new Callback(this); dialog3.StartWaitDialogWithCallback( szWaitCaption: _title, szWaitMessage: this.ProgressTracker.Description ?? _message, szProgressText: null, varStatusBmpAnim: null, szStatusBarText: null, fIsCancelable: _allowCancel, iDelayToShowDialog: DelayToShowDialogSecs, fShowProgress: showProgress, iTotalSteps: this.ProgressTracker.TotalItems, iCurrentStep: this.ProgressTracker.CompletedItems, pCallback: callback); return dialog3; } public CancellationToken CancellationToken { get { return _allowCancel ? _cancellationTokenSource.Token : CancellationToken.None; } } public string Message { get { return _message; } set { _message = value; UpdateDialog(); } } public bool AllowCancel { get { return _allowCancel; } set { _allowCancel = value; UpdateDialog(); } } private void UpdateDialog() { ((IVsThreadedWaitDialog2)_dialog).UpdateProgress( this.ProgressTracker.Description ?? _message, szProgressText: null, szStatusBarText: null, iCurrentStep: this.ProgressTracker.CompletedItems, iTotalSteps: this.ProgressTracker.TotalItems, fDisableCancel: !_allowCancel, pfCanceled: out _); } public void Dispose() { _dialog.EndWaitDialog(out var canceled); // Let the global operation object know that we completed with/without user cancelling. If the user // canceled, we won't call 'Done', and so calling 'Dispose' will log that we didn't complete fully. if (canceled == 0) _registration.Done(); _registration.Dispose(); } private void OnCanceled() { if (_allowCancel) { _cancellationTokenSource.Cancel(); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/BasicBlockExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Operations; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal static partial class BasicBlockExtensions { public static IEnumerable<IOperation> DescendantOperations(this BasicBlock basicBlock) { foreach (var statement in basicBlock.Operations) { foreach (var operation in statement.DescendantsAndSelf()) { yield return operation; } } if (basicBlock.BranchValue != null) { foreach (var operation in basicBlock.BranchValue.DescendantsAndSelf()) { yield return operation; } } } } }
// Licensed to the .NET Foundation under one or more 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.Operations; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal static partial class BasicBlockExtensions { public static IEnumerable<IOperation> DescendantOperations(this BasicBlock basicBlock) { foreach (var statement in basicBlock.Operations) { foreach (var operation in statement.DescendantsAndSelf()) { yield return operation; } } if (basicBlock.BranchValue != null) { foreach (var operation in basicBlock.BranchValue.DescendantsAndSelf()) { yield return operation; } } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/RealParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A set of utilities for converting from a decimal floating-point literal string to its IEEE float /// or double representation, which considers all digits significant and correctly rounds according to /// the IEEE round-to-nearest-ties-to-even mode. This code does not support a leading sign character, /// as that is not part of the C# or VB floating-point literal lexical syntax. /// /// If you change this code, please run the set of long-running random tests in the solution /// RandomRealParserTests.sln. That solution is not included in Roslyn.sln as it is Windows-specific. /// </summary> internal static class RealParser { /// <summary> /// Try parsing a correctly-formatted double floating-point literal into the nearest representable double /// using IEEE round-to-nearest-ties-to-even rounding mode. Behavior is not defined for inputs that are /// not valid C# floating-point literals. /// </summary> /// <param name="s">The decimal floating-point constant's string</param> /// <param name="d">The nearest double value, if conversion succeeds</param> /// <returns>True if the input was converted; false if there was an overflow</returns> public static bool TryParseDouble(string s, out double d) { var str = DecimalFloatingPointString.FromSource(s); var dbl = DoubleFloatingPointType.Instance; ulong result; var status = RealParser.ConvertDecimalToFloatingPointBits(str, dbl, out result); d = BitConverter.Int64BitsToDouble((long)result); return status != Status.Overflow; } /// <summary> /// Try parsing a correctly-formatted float floating-point literal into the nearest representable float /// using IEEE round-to-nearest-ties-to-even rounding mode. Behavior is not defined for inputs that are /// not valid C# floating-point literals. /// </summary> /// <param name="s">The float floating-point constant's string</param> /// <param name="f">The nearest float value, if conversion succeeds</param> /// <returns>True if the input was converted; false if there was an overflow</returns> public static bool TryParseFloat(string s, out float f) { var str = DecimalFloatingPointString.FromSource(s); var dbl = FloatFloatingPointType.Instance; ulong result; var status = RealParser.ConvertDecimalToFloatingPointBits(str, dbl, out result); f = Int32BitsToFloat((uint)result); return status != Status.Overflow; } private static readonly BigInteger s_bigZero = BigInteger.Zero; private static readonly BigInteger s_bigOne = BigInteger.One; private static readonly BigInteger s_bigTwo = new BigInteger(2); private static readonly BigInteger s_bigTen = new BigInteger(10); /// <summary> /// Properties of an IEEE floating-point representation. /// </summary> private abstract class FloatingPointType { public abstract ushort DenormalMantissaBits { get; } public ushort NormalMantissaBits => (ushort)(DenormalMantissaBits + 1); // we get an extra (hidden) bit for normal mantissas public abstract ushort ExponentBits { get; } public int MinBinaryExponent => 1 - MaxBinaryExponent; public abstract int MaxBinaryExponent { get; } public int OverflowDecimalExponent => (MaxBinaryExponent + 2 * NormalMantissaBits) / 3; public abstract int ExponentBias { get; } public ulong DenormalMantissaMask => (1UL << (DenormalMantissaBits)) - 1; public ulong NormalMantissaMask => (1UL << NormalMantissaBits) - 1; public abstract ulong Zero { get; } public abstract ulong Infinity { get; } /// <summary> /// Converts the floating point value 0.mantissa * 2^exponent into the /// correct form for the FloatingPointType and stores the bits of the resulting value /// into the result object. /// The caller must ensure that the mantissa and exponent are correctly computed /// such that either [1] the most significant bit of the mantissa is in the /// correct position for the FloatingType, or [2] the exponent has been correctly /// adjusted to account for the shift of the mantissa that will be required. /// /// This function correctly handles range errors and stores a zero or infinity in /// the result object on underflow and overflow errors, respectively. This /// function correctly forms denormal numbers when required. /// /// If the provided mantissa has more bits of precision than can be stored in the /// result object, the mantissa is rounded to the available precision. Thus, if /// possible, the caller should provide a mantissa with at least one more bit of /// precision than is required, to ensure that the mantissa is correctly rounded. /// (The caller should not round the mantissa before calling this function.) /// </summary> /// <param name="initialMantissa">The bits of the mantissa</param> /// <param name="initialExponent">The exponent</param> /// <param name="hasZeroTail">Whether there are any nonzero bits past the supplied mantissa</param> /// <param name="result">Where the bits of the floating-point number are stored</param> /// <returns>A status indicating whether the conversion succeeded and why</returns> public Status AssembleFloatingPointValue( ulong initialMantissa, int initialExponent, bool hasZeroTail, out ulong result) { // number of bits by which we must adjust the mantissa to shift it into the // correct position, and compute the resulting base two exponent for the // normalized mantissa: uint initialMantissaBits = CountSignificantBits(initialMantissa); int normalMantissaShift = this.NormalMantissaBits - (int)initialMantissaBits; int normalExponent = initialExponent - normalMantissaShift; ulong mantissa = initialMantissa; int exponent = normalExponent; if (normalExponent > this.MaxBinaryExponent) { // The exponent is too large to be represented by the floating point // type; report the overflow condition: result = this.Infinity; return Status.Overflow; } else if (normalExponent < this.MinBinaryExponent) { // The exponent is too small to be represented by the floating point // type as a normal value, but it may be representable as a denormal // value. Compute the number of bits by which we need to shift the // mantissa in order to form a denormal number. (The subtraction of // an extra 1 is to account for the hidden bit of the mantissa that // is not available for use when representing a denormal.) int denormalMantissaShift = normalMantissaShift + normalExponent + this.ExponentBias - 1; // Denormal values have an exponent of zero, so the debiased exponent is // the negation of the exponent bias: exponent = -this.ExponentBias; if (denormalMantissaShift < 0) { // Use two steps for right shifts: for a shift of N bits, we first // shift by N-1 bits, then shift the last bit and use its value to // round the mantissa. mantissa = RightShiftWithRounding(mantissa, -denormalMantissaShift, hasZeroTail); // If the mantissa is now zero, we have underflowed: if (mantissa == 0) { result = this.Zero; return Status.Underflow; } // When we round the mantissa, the result may be so large that the // number becomes a normal value. For example, consider the single // precision case where the mantissa is 0x01ffffff and a right shift // of 2 is required to shift the value into position. We perform the // shift in two steps: we shift by one bit, then we shift again and // round using the dropped bit. The initial shift yields 0x00ffffff. // The rounding shift then yields 0x007fffff and because the least // significant bit was 1, we add 1 to this number to round it. The // final result is 0x00800000. // // 0x00800000 is 24 bits, which is more than the 23 bits available // in the mantissa. Thus, we have rounded our denormal number into // a normal number. // // We detect this case here and re-adjust the mantissa and exponent // appropriately, to form a normal number: if (mantissa > this.DenormalMantissaMask) { // We add one to the denormal_mantissa_shift to account for the // hidden mantissa bit (we subtracted one to account for this bit // when we computed the denormal_mantissa_shift above). exponent = initialExponent - (denormalMantissaShift + 1) - normalMantissaShift; } } else { mantissa <<= denormalMantissaShift; } } else { if (normalMantissaShift < 0) { // Use two steps for right shifts: for a shift of N bits, we first // shift by N-1 bits, then shift the last bit and use its value to // round the mantissa. mantissa = RightShiftWithRounding(mantissa, -normalMantissaShift, hasZeroTail); // When we round the mantissa, it may produce a result that is too // large. In this case, we divide the mantissa by two and increment // the exponent (this does not change the value). if (mantissa > this.NormalMantissaMask) { mantissa >>= 1; ++exponent; // The increment of the exponent may have generated a value too // large to be represented. In this case, report the overflow: if (exponent > this.MaxBinaryExponent) { result = this.Infinity; return Status.Overflow; } } } else if (normalMantissaShift > 0) { mantissa <<= normalMantissaShift; } } // Unset the hidden bit in the mantissa and assemble the floating point value // from the computed components: mantissa &= this.DenormalMantissaMask; Debug.Assert((DenormalMantissaMask & (1UL << DenormalMantissaBits)) == 0); ulong shiftedExponent = ((ulong)(exponent + this.ExponentBias)) << DenormalMantissaBits; Debug.Assert((shiftedExponent & DenormalMantissaMask) == 0); Debug.Assert((mantissa & ~DenormalMantissaMask) == 0); Debug.Assert((shiftedExponent & ~(((1UL << this.ExponentBits) - 1) << DenormalMantissaBits)) == 0); // exponent fits in its place result = shiftedExponent | mantissa; return Status.OK; } } /// <summary> /// Properties of a C# float. /// </summary> private sealed class FloatFloatingPointType : FloatingPointType { public static FloatFloatingPointType Instance = new FloatFloatingPointType(); private FloatFloatingPointType() { } public override ushort DenormalMantissaBits => 23; public override ushort ExponentBits => 8; public override int MaxBinaryExponent => 127; public override int ExponentBias => 127; public override ulong Zero => FloatToInt32Bits(0.0f); public override ulong Infinity => FloatToInt32Bits(float.PositiveInfinity); } /// <summary> /// Properties of a C# double. /// </summary> private sealed class DoubleFloatingPointType : FloatingPointType { public static DoubleFloatingPointType Instance = new DoubleFloatingPointType(); private DoubleFloatingPointType() { } public override ushort DenormalMantissaBits => 52; public override ushort ExponentBits => 11; public override int MaxBinaryExponent => 1023; public override int ExponentBias => 1023; public override ulong Zero => (ulong)BitConverter.DoubleToInt64Bits(0.0d); public override ulong Infinity => (ulong)BitConverter.DoubleToInt64Bits(double.PositiveInfinity); } /// <summary> /// This type is used to hold a partially-parsed string representation of a /// floating point number. The number is stored in the following form: /// <pre> /// 0.Mantissa * 10^Exponent /// </pre> /// The Mantissa buffer stores the mantissa digits as characters in a string. /// The MantissaCount gives the number of digits present in the Mantissa buffer. /// There shall be neither leading nor trailing zero digits in the Mantissa. /// Note that this represents only nonnegative floating-point literals; the /// negative sign in C# and VB is actually a separate unary negation operator. /// </summary> [DebuggerDisplay("0.{Mantissa}e{Exponent}")] private struct DecimalFloatingPointString { public int Exponent; public string Mantissa; public uint MantissaCount => (uint)Mantissa.Length; /// <summary> /// Create a DecimalFloatingPointString from a string representing a floating-point literal. /// </summary> /// <param name="source">The text of the floating-point literal</param> public static DecimalFloatingPointString FromSource(string source) { var mantissaBuilder = new StringBuilder(); var exponent = 0; int i = 0; while (i < source.Length && source[i] == '0') i++; int skippedDecimals = 0; while (i < source.Length && source[i] >= '0' && source[i] <= '9') { if (source[i] == '0') { skippedDecimals++; } else { mantissaBuilder.Append('0', skippedDecimals); skippedDecimals = 0; mantissaBuilder.Append(source[i]); } exponent++; i++; } if (i < source.Length && source[i] == '.') { i++; while (i < source.Length && source[i] >= '0' && source[i] <= '9') { if (source[i] == '0') { skippedDecimals++; } else { mantissaBuilder.Append('0', skippedDecimals); skippedDecimals = 0; mantissaBuilder.Append(source[i]); } i++; } } var result = default(DecimalFloatingPointString); result.Mantissa = mantissaBuilder.ToString(); if (i < source.Length && (source[i] == 'e' || source[i] == 'E')) { const int MAX_EXP = (1 << 30); // even playing ground char exponentSign = '\0'; i++; if (i < source.Length && (source[i] == '-' || source[i] == '+')) { exponentSign = source[i]; i++; } int firstExponent = i; int lastExponent = i; while (i < source.Length && source[i] >= '0' && source[i] <= '9') lastExponent = ++i; int exponentMagnitude = 0; if (int.TryParse(source.Substring(firstExponent, lastExponent - firstExponent), out exponentMagnitude) && exponentMagnitude <= MAX_EXP) { if (exponentSign == '-') { exponent -= exponentMagnitude; } else { exponent += exponentMagnitude; } } else { exponent = exponentSign == '-' ? -MAX_EXP : MAX_EXP; } } result.Exponent = exponent; return result; } } private enum Status { OK, NoDigits, Underflow, Overflow } /// <summary> /// Convert a DecimalFloatingPointString to the bits of the given floating-point type. /// </summary> private static Status ConvertDecimalToFloatingPointBits(DecimalFloatingPointString data, FloatingPointType type, out ulong result) { if (data.Mantissa.Length == 0) { result = type.Zero; return Status.NoDigits; } // To generate an N bit mantissa we require N + 1 bits of precision. The // extra bit is used to correctly round the mantissa (if there are fewer bits // than this available, then that's totally okay; in that case we use what we // have and we don't need to round). uint requiredBitsOfPrecision = (uint)type.NormalMantissaBits + 1; // The input is of the form 0.Mantissa x 10^Exponent, where 'Mantissa' are // the decimal digits of the mantissa and 'Exponent' is the decimal exponent. // We decompose the mantissa into two parts: an integer part and a fractional // part. If the exponent is positive, then the integer part consists of the // first 'exponent' digits, or all present digits if there are fewer digits. // If the exponent is zero or negative, then the integer part is empty. In // either case, the remaining digits form the fractional part of the mantissa. uint positiveExponent = (uint)Math.Max(0, data.Exponent); uint integerDigitsPresent = Math.Min(positiveExponent, data.MantissaCount); uint integerDigitsMissing = positiveExponent - integerDigitsPresent; uint integerFirstIndex = 0; uint integerLastIndex = integerDigitsPresent; uint fractionalFirstIndex = integerLastIndex; uint fractionalLastIndex = data.MantissaCount; uint fractionalDigitsPresent = fractionalLastIndex - fractionalFirstIndex; // First, we accumulate the integer part of the mantissa into a big_integer: BigInteger integerValue = AccumulateDecimalDigitsIntoBigInteger(data, integerFirstIndex, integerLastIndex); if (integerDigitsMissing > 0) { if (integerDigitsMissing > type.OverflowDecimalExponent) { result = type.Infinity; return Status.Overflow; } MultiplyByPowerOfTen(ref integerValue, integerDigitsMissing); } // At this point, the integer_value contains the value of the integer part // of the mantissa. If either [1] this number has more than the required // number of bits of precision or [2] the mantissa has no fractional part, // then we can assemble the result immediately: byte[] integerValueAsBytes; uint integerBitsOfPrecision = CountSignificantBits(integerValue, out integerValueAsBytes); if (integerBitsOfPrecision >= requiredBitsOfPrecision || fractionalDigitsPresent == 0) { return ConvertBigIntegerToFloatingPointBits( integerValueAsBytes, integerBitsOfPrecision, fractionalDigitsPresent != 0, type, out result); } // Otherwise, we did not get enough bits of precision from the integer part, // and the mantissa has a fractional part. We parse the fractional part of // the mantissa to obtain more bits of precision. To do this, we convert // the fractional part into an actual fraction N/M, where the numerator N is // computed from the digits of the fractional part, and the denominator M is // computed as the power of 10 such that N/M is equal to the value of the // fractional part of the mantissa. uint fractionalDenominatorExponent = data.Exponent < 0 ? fractionalDigitsPresent + (uint)-data.Exponent : fractionalDigitsPresent; if (integerBitsOfPrecision == 0 && (fractionalDenominatorExponent - (int)data.MantissaCount) > type.OverflowDecimalExponent) { // If there were any digits in the integer part, it is impossible to // underflow (because the exponent cannot possibly be small enough), // so if we underflow here it is a true underflow and we return zero. result = type.Zero; return Status.Underflow; } BigInteger fractionalNumerator = AccumulateDecimalDigitsIntoBigInteger(data, fractionalFirstIndex, fractionalLastIndex); Debug.Assert(!fractionalNumerator.IsZero); BigInteger fractionalDenominator = s_bigOne; MultiplyByPowerOfTen(ref fractionalDenominator, fractionalDenominatorExponent); // Because we are using only the fractional part of the mantissa here, the // numerator is guaranteed to be smaller than the denominator. We normalize // the fraction such that the most significant bit of the numerator is in // the same position as the most significant bit in the denominator. This // ensures that when we later shift the numerator N bits to the left, we // will produce N bits of precision. uint fractionalNumeratorBits = CountSignificantBits(fractionalNumerator); uint fractionalDenominatorBits = CountSignificantBits(fractionalDenominator); uint fractionalShift = fractionalDenominatorBits > fractionalNumeratorBits ? fractionalDenominatorBits - fractionalNumeratorBits : 0; if (fractionalShift > 0) { ShiftLeft(ref fractionalNumerator, fractionalShift); } uint requiredFractionalBitsOfPrecision = requiredBitsOfPrecision - integerBitsOfPrecision; uint remainingBitsOfPrecisionRequired = requiredFractionalBitsOfPrecision; if (integerBitsOfPrecision > 0) { // If the fractional part of the mantissa provides no bits of precision // and cannot affect rounding, we can just take whatever bits we got from // the integer part of the mantissa. This is the case for numbers like // 5.0000000000000000000001, where the significant digits of the fractional // part start so far to the right that they do not affect the floating // point representation. // // If the fractional shift is exactly equal to the number of bits of // precision that we require, then no fractional bits will be part of the // result, but the result may affect rounding. This is e.g. the case for // large, odd integers with a fractional part greater than or equal to .5. // Thus, we need to do the division to correctly round the result. if (fractionalShift > remainingBitsOfPrecisionRequired) { return ConvertBigIntegerToFloatingPointBits( integerValueAsBytes, integerBitsOfPrecision, fractionalDigitsPresent != 0, type, out result); } remainingBitsOfPrecisionRequired -= fractionalShift; } // If there was no integer part of the mantissa, we will need to compute the // exponent from the fractional part. The fractional exponent is the power // of two by which we must multiply the fractional part to move it into the // range [1.0, 2.0). This will either be the same as the shift we computed // earlier, or one greater than that shift: uint fractionalExponent = fractionalNumerator < fractionalDenominator ? fractionalShift + 1 : fractionalShift; ShiftLeft(ref fractionalNumerator, remainingBitsOfPrecisionRequired); BigInteger fractionalRemainder; BigInteger bigFractionalMantissa = BigInteger.DivRem(fractionalNumerator, fractionalDenominator, out fractionalRemainder); ulong fractionalMantissa = (ulong)bigFractionalMantissa; bool hasZeroTail = fractionalRemainder.IsZero; // We may have produced more bits of precision than were required. Check, // and remove any "extra" bits: uint fractionalMantissaBits = CountSignificantBits(fractionalMantissa); if (fractionalMantissaBits > requiredFractionalBitsOfPrecision) { int shift = (int)(fractionalMantissaBits - requiredFractionalBitsOfPrecision); hasZeroTail = hasZeroTail && (fractionalMantissa & ((1UL << shift) - 1)) == 0; fractionalMantissa >>= shift; } // Compose the mantissa from the integer and fractional parts: Debug.Assert(integerBitsOfPrecision < 60); // we can use BigInteger's built-in conversion ulong integerMantissa = (ulong)integerValue; ulong completeMantissa = (integerMantissa << (int)requiredFractionalBitsOfPrecision) + fractionalMantissa; // Compute the final exponent: // * If the mantissa had an integer part, then the exponent is one less than // the number of bits we obtained from the integer part. (It's one less // because we are converting to the form 1.11111, with one 1 to the left // of the decimal point.) // * If the mantissa had no integer part, then the exponent is the fractional // exponent that we computed. // Then, in both cases, we subtract an additional one from the exponent, to // account for the fact that we've generated an extra bit of precision, for // use in rounding. int finalExponent = integerBitsOfPrecision > 0 ? (int)integerBitsOfPrecision - 2 : -(int)(fractionalExponent) - 1; return type.AssembleFloatingPointValue(completeMantissa, finalExponent, hasZeroTail, out result); } /// <summary> /// This function is part of the fast track for integer floating point strings. /// It takes an integer stored as an array of bytes (lsb first) and converts the value into its FloatingType /// representation, storing the bits into "result". If the value is not /// representable, +/-infinity is stored and overflow is reported (since this /// function only deals with integers, underflow is impossible). /// </summary> /// <param name="integerValueAsBytes">the bits of the integer, least significant bits first</param> /// <param name="integerBitsOfPrecision">the number of bits of precision in integerValueAsBytes</param> /// <param name="hasNonzeroFractionalPart">whether there are nonzero digits after the decimal</param> /// <param name="type">the kind of real number to build</param> /// <param name="result">the result</param> /// <returns>An indicator of the kind of result</returns> private static Status ConvertBigIntegerToFloatingPointBits(byte[] integerValueAsBytes, uint integerBitsOfPrecision, bool hasNonzeroFractionalPart, FloatingPointType type, out ulong result) { int baseExponent = type.DenormalMantissaBits; int exponent; ulong mantissa; bool has_zero_tail = !hasNonzeroFractionalPart; int topElementIndex = ((int)integerBitsOfPrecision - 1) / 8; // The high-order byte of integerValueAsBytes might not have a full eight bits. However, // since the data are stored in quanta of 8 bits, and we really only need around 54 // bits of mantissa for a double (and fewer for a float), we can just assemble data // from the eight high-order bytes and we will get between 59 and 64 bits, which is more // than enough. int bottomElementIndex = Math.Max(0, topElementIndex - (64 / 8) + 1); exponent = baseExponent + bottomElementIndex * 8; mantissa = 0; for (int i = (int)topElementIndex; i >= bottomElementIndex; i--) { mantissa <<= 8; mantissa |= integerValueAsBytes[i]; } for (int i = bottomElementIndex - 1; has_zero_tail && i >= 0; i--) { if (integerValueAsBytes[i] != 0) has_zero_tail = false; } return type.AssembleFloatingPointValue(mantissa, exponent, has_zero_tail, out result); } /// <summary> /// Parse a sequence of digits into a BigInteger. /// </summary> /// <param name="data">The DecimalFloatingPointString containing the digits in its Mantissa</param> /// <param name="integer_first_index">The index of the first digit to convert</param> /// <param name="integer_last_index">The index just past the last digit to convert</param> /// <returns>The BigInteger result</returns> private static BigInteger AccumulateDecimalDigitsIntoBigInteger(DecimalFloatingPointString data, uint integer_first_index, uint integer_last_index) { if (integer_first_index == integer_last_index) return s_bigZero; var valueString = data.Mantissa.Substring((int)integer_first_index, (int)(integer_last_index - integer_first_index)); return BigInteger.Parse(valueString); } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(ulong data) { uint result = 0; while (data != 0) { data >>= 1; result++; } return result; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(byte data) { uint result = 0; while (data != 0) { data >>= 1; result++; } return result; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(BigInteger data, out byte[] dataBytes) { if (data.IsZero) { dataBytes = new byte[1]; return 0; } dataBytes = data.ToByteArray(); // the bits of the BigInteger, least significant bits first for (int i = dataBytes.Length - 1; i >= 0; i--) { var v = dataBytes[i]; if (v != 0) return 8 * (uint)i + CountSignificantBits(v); } return 0; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(BigInteger data) { byte[] dataBytes; return CountSignificantBits(data, out dataBytes); } /// <summary> /// Computes value / 2^shift, then rounds the result according to the current /// rounding mode. By the time we call this function, we will already have /// discarded most digits. The caller must pass true for has_zero_tail if /// all discarded bits were zeroes. /// </summary> /// <param name="value">The value to shift</param> /// <param name="shift">The amount of shift</param> /// <param name="hasZeroTail">Whether there are any less significant nonzero bits in the value</param> /// <returns></returns> private static ulong RightShiftWithRounding(ulong value, int shift, bool hasZeroTail) { // If we'd need to shift further than it is possible to shift, the answer // is always zero: if (shift >= 64) return 0; ulong extraBitsMask = (1UL << (shift - 1)) - 1; ulong roundBitMask = (1UL << (shift - 1)); ulong lsbBitMask = 1UL << shift; bool lsbBit = (value & lsbBitMask) != 0; bool roundBit = (value & roundBitMask) != 0; bool hasTailBits = !hasZeroTail || (value & extraBitsMask) != 0; return (value >> shift) + (ShouldRoundUp(lsbBit: lsbBit, roundBit: roundBit, hasTailBits: hasTailBits) ? 1UL : 0); } /// <summary> /// Determines whether a mantissa should be rounded up in the /// round-to-nearest-ties-to-even mode given [1] the value of the least /// significant bit of the mantissa, [2] the value of the next bit after /// the least significant bit (the "round" bit) and [3] whether any /// trailing bits after the round bit are set. /// /// The mantissa is treated as an unsigned integer magnitude. /// /// For this function, "round up" is defined as "increase the magnitude" of the /// mantissa. /// </summary> /// <param name="lsbBit">the least-significant bit of the representable value</param> /// <param name="roundBit">the bit following the least-significant bit</param> /// <param name="hasTailBits">true if there are any (less significant) bits set following roundBit</param> /// <returns></returns> private static bool ShouldRoundUp( bool lsbBit, bool roundBit, bool hasTailBits) { // If there are insignificant set bits, we need to round to the // nearest; there are two cases: // we round up if either [1] the value is slightly greater than the midpoint // between two exactly representable values or [2] the value is exactly the // midpoint between two exactly representable values and the greater of the // two is even (this is "round-to-even"). return roundBit && (hasTailBits || lsbBit); } /// <summary> /// Multiply a BigInteger by the given power of two. /// </summary> /// <param name="number">The BigInteger to multiply by a power of two and replace with the product</param> /// <param name="shift">The power of two to multiply it by</param> private static void ShiftLeft(ref BigInteger number, uint shift) { var powerOfTwo = BigInteger.Pow(s_bigTwo, (int)shift); number = number * powerOfTwo; } /// <summary> /// Multiply a BigInteger by the given power of ten. /// </summary> /// <param name="number">The BigInteger to multiply by a power of ten and replace with the product</param> /// <param name="power">The power of ten to multiply it by</param> private static void MultiplyByPowerOfTen(ref BigInteger number, uint power) { var powerOfTen = BigInteger.Pow(s_bigTen, (int)power); number = number * powerOfTen; } /// <summary> /// Convert a float value to the bits of its representation /// </summary> private static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } /// <summary> /// Convert the bits of its representation to a float /// </summary> private static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } /// <summary> /// A union used to convert between a float and the bits of its representation /// </summary> [StructLayout(LayoutKind.Explicit)] private struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A set of utilities for converting from a decimal floating-point literal string to its IEEE float /// or double representation, which considers all digits significant and correctly rounds according to /// the IEEE round-to-nearest-ties-to-even mode. This code does not support a leading sign character, /// as that is not part of the C# or VB floating-point literal lexical syntax. /// /// If you change this code, please run the set of long-running random tests in the solution /// RandomRealParserTests.sln. That solution is not included in Roslyn.sln as it is Windows-specific. /// </summary> internal static class RealParser { /// <summary> /// Try parsing a correctly-formatted double floating-point literal into the nearest representable double /// using IEEE round-to-nearest-ties-to-even rounding mode. Behavior is not defined for inputs that are /// not valid C# floating-point literals. /// </summary> /// <param name="s">The decimal floating-point constant's string</param> /// <param name="d">The nearest double value, if conversion succeeds</param> /// <returns>True if the input was converted; false if there was an overflow</returns> public static bool TryParseDouble(string s, out double d) { var str = DecimalFloatingPointString.FromSource(s); var dbl = DoubleFloatingPointType.Instance; ulong result; var status = RealParser.ConvertDecimalToFloatingPointBits(str, dbl, out result); d = BitConverter.Int64BitsToDouble((long)result); return status != Status.Overflow; } /// <summary> /// Try parsing a correctly-formatted float floating-point literal into the nearest representable float /// using IEEE round-to-nearest-ties-to-even rounding mode. Behavior is not defined for inputs that are /// not valid C# floating-point literals. /// </summary> /// <param name="s">The float floating-point constant's string</param> /// <param name="f">The nearest float value, if conversion succeeds</param> /// <returns>True if the input was converted; false if there was an overflow</returns> public static bool TryParseFloat(string s, out float f) { var str = DecimalFloatingPointString.FromSource(s); var dbl = FloatFloatingPointType.Instance; ulong result; var status = RealParser.ConvertDecimalToFloatingPointBits(str, dbl, out result); f = Int32BitsToFloat((uint)result); return status != Status.Overflow; } private static readonly BigInteger s_bigZero = BigInteger.Zero; private static readonly BigInteger s_bigOne = BigInteger.One; private static readonly BigInteger s_bigTwo = new BigInteger(2); private static readonly BigInteger s_bigTen = new BigInteger(10); /// <summary> /// Properties of an IEEE floating-point representation. /// </summary> private abstract class FloatingPointType { public abstract ushort DenormalMantissaBits { get; } public ushort NormalMantissaBits => (ushort)(DenormalMantissaBits + 1); // we get an extra (hidden) bit for normal mantissas public abstract ushort ExponentBits { get; } public int MinBinaryExponent => 1 - MaxBinaryExponent; public abstract int MaxBinaryExponent { get; } public int OverflowDecimalExponent => (MaxBinaryExponent + 2 * NormalMantissaBits) / 3; public abstract int ExponentBias { get; } public ulong DenormalMantissaMask => (1UL << (DenormalMantissaBits)) - 1; public ulong NormalMantissaMask => (1UL << NormalMantissaBits) - 1; public abstract ulong Zero { get; } public abstract ulong Infinity { get; } /// <summary> /// Converts the floating point value 0.mantissa * 2^exponent into the /// correct form for the FloatingPointType and stores the bits of the resulting value /// into the result object. /// The caller must ensure that the mantissa and exponent are correctly computed /// such that either [1] the most significant bit of the mantissa is in the /// correct position for the FloatingType, or [2] the exponent has been correctly /// adjusted to account for the shift of the mantissa that will be required. /// /// This function correctly handles range errors and stores a zero or infinity in /// the result object on underflow and overflow errors, respectively. This /// function correctly forms denormal numbers when required. /// /// If the provided mantissa has more bits of precision than can be stored in the /// result object, the mantissa is rounded to the available precision. Thus, if /// possible, the caller should provide a mantissa with at least one more bit of /// precision than is required, to ensure that the mantissa is correctly rounded. /// (The caller should not round the mantissa before calling this function.) /// </summary> /// <param name="initialMantissa">The bits of the mantissa</param> /// <param name="initialExponent">The exponent</param> /// <param name="hasZeroTail">Whether there are any nonzero bits past the supplied mantissa</param> /// <param name="result">Where the bits of the floating-point number are stored</param> /// <returns>A status indicating whether the conversion succeeded and why</returns> public Status AssembleFloatingPointValue( ulong initialMantissa, int initialExponent, bool hasZeroTail, out ulong result) { // number of bits by which we must adjust the mantissa to shift it into the // correct position, and compute the resulting base two exponent for the // normalized mantissa: uint initialMantissaBits = CountSignificantBits(initialMantissa); int normalMantissaShift = this.NormalMantissaBits - (int)initialMantissaBits; int normalExponent = initialExponent - normalMantissaShift; ulong mantissa = initialMantissa; int exponent = normalExponent; if (normalExponent > this.MaxBinaryExponent) { // The exponent is too large to be represented by the floating point // type; report the overflow condition: result = this.Infinity; return Status.Overflow; } else if (normalExponent < this.MinBinaryExponent) { // The exponent is too small to be represented by the floating point // type as a normal value, but it may be representable as a denormal // value. Compute the number of bits by which we need to shift the // mantissa in order to form a denormal number. (The subtraction of // an extra 1 is to account for the hidden bit of the mantissa that // is not available for use when representing a denormal.) int denormalMantissaShift = normalMantissaShift + normalExponent + this.ExponentBias - 1; // Denormal values have an exponent of zero, so the debiased exponent is // the negation of the exponent bias: exponent = -this.ExponentBias; if (denormalMantissaShift < 0) { // Use two steps for right shifts: for a shift of N bits, we first // shift by N-1 bits, then shift the last bit and use its value to // round the mantissa. mantissa = RightShiftWithRounding(mantissa, -denormalMantissaShift, hasZeroTail); // If the mantissa is now zero, we have underflowed: if (mantissa == 0) { result = this.Zero; return Status.Underflow; } // When we round the mantissa, the result may be so large that the // number becomes a normal value. For example, consider the single // precision case where the mantissa is 0x01ffffff and a right shift // of 2 is required to shift the value into position. We perform the // shift in two steps: we shift by one bit, then we shift again and // round using the dropped bit. The initial shift yields 0x00ffffff. // The rounding shift then yields 0x007fffff and because the least // significant bit was 1, we add 1 to this number to round it. The // final result is 0x00800000. // // 0x00800000 is 24 bits, which is more than the 23 bits available // in the mantissa. Thus, we have rounded our denormal number into // a normal number. // // We detect this case here and re-adjust the mantissa and exponent // appropriately, to form a normal number: if (mantissa > this.DenormalMantissaMask) { // We add one to the denormal_mantissa_shift to account for the // hidden mantissa bit (we subtracted one to account for this bit // when we computed the denormal_mantissa_shift above). exponent = initialExponent - (denormalMantissaShift + 1) - normalMantissaShift; } } else { mantissa <<= denormalMantissaShift; } } else { if (normalMantissaShift < 0) { // Use two steps for right shifts: for a shift of N bits, we first // shift by N-1 bits, then shift the last bit and use its value to // round the mantissa. mantissa = RightShiftWithRounding(mantissa, -normalMantissaShift, hasZeroTail); // When we round the mantissa, it may produce a result that is too // large. In this case, we divide the mantissa by two and increment // the exponent (this does not change the value). if (mantissa > this.NormalMantissaMask) { mantissa >>= 1; ++exponent; // The increment of the exponent may have generated a value too // large to be represented. In this case, report the overflow: if (exponent > this.MaxBinaryExponent) { result = this.Infinity; return Status.Overflow; } } } else if (normalMantissaShift > 0) { mantissa <<= normalMantissaShift; } } // Unset the hidden bit in the mantissa and assemble the floating point value // from the computed components: mantissa &= this.DenormalMantissaMask; Debug.Assert((DenormalMantissaMask & (1UL << DenormalMantissaBits)) == 0); ulong shiftedExponent = ((ulong)(exponent + this.ExponentBias)) << DenormalMantissaBits; Debug.Assert((shiftedExponent & DenormalMantissaMask) == 0); Debug.Assert((mantissa & ~DenormalMantissaMask) == 0); Debug.Assert((shiftedExponent & ~(((1UL << this.ExponentBits) - 1) << DenormalMantissaBits)) == 0); // exponent fits in its place result = shiftedExponent | mantissa; return Status.OK; } } /// <summary> /// Properties of a C# float. /// </summary> private sealed class FloatFloatingPointType : FloatingPointType { public static FloatFloatingPointType Instance = new FloatFloatingPointType(); private FloatFloatingPointType() { } public override ushort DenormalMantissaBits => 23; public override ushort ExponentBits => 8; public override int MaxBinaryExponent => 127; public override int ExponentBias => 127; public override ulong Zero => FloatToInt32Bits(0.0f); public override ulong Infinity => FloatToInt32Bits(float.PositiveInfinity); } /// <summary> /// Properties of a C# double. /// </summary> private sealed class DoubleFloatingPointType : FloatingPointType { public static DoubleFloatingPointType Instance = new DoubleFloatingPointType(); private DoubleFloatingPointType() { } public override ushort DenormalMantissaBits => 52; public override ushort ExponentBits => 11; public override int MaxBinaryExponent => 1023; public override int ExponentBias => 1023; public override ulong Zero => (ulong)BitConverter.DoubleToInt64Bits(0.0d); public override ulong Infinity => (ulong)BitConverter.DoubleToInt64Bits(double.PositiveInfinity); } /// <summary> /// This type is used to hold a partially-parsed string representation of a /// floating point number. The number is stored in the following form: /// <pre> /// 0.Mantissa * 10^Exponent /// </pre> /// The Mantissa buffer stores the mantissa digits as characters in a string. /// The MantissaCount gives the number of digits present in the Mantissa buffer. /// There shall be neither leading nor trailing zero digits in the Mantissa. /// Note that this represents only nonnegative floating-point literals; the /// negative sign in C# and VB is actually a separate unary negation operator. /// </summary> [DebuggerDisplay("0.{Mantissa}e{Exponent}")] private struct DecimalFloatingPointString { public int Exponent; public string Mantissa; public uint MantissaCount => (uint)Mantissa.Length; /// <summary> /// Create a DecimalFloatingPointString from a string representing a floating-point literal. /// </summary> /// <param name="source">The text of the floating-point literal</param> public static DecimalFloatingPointString FromSource(string source) { var mantissaBuilder = new StringBuilder(); var exponent = 0; int i = 0; while (i < source.Length && source[i] == '0') i++; int skippedDecimals = 0; while (i < source.Length && source[i] >= '0' && source[i] <= '9') { if (source[i] == '0') { skippedDecimals++; } else { mantissaBuilder.Append('0', skippedDecimals); skippedDecimals = 0; mantissaBuilder.Append(source[i]); } exponent++; i++; } if (i < source.Length && source[i] == '.') { i++; while (i < source.Length && source[i] >= '0' && source[i] <= '9') { if (source[i] == '0') { skippedDecimals++; } else { mantissaBuilder.Append('0', skippedDecimals); skippedDecimals = 0; mantissaBuilder.Append(source[i]); } i++; } } var result = default(DecimalFloatingPointString); result.Mantissa = mantissaBuilder.ToString(); if (i < source.Length && (source[i] == 'e' || source[i] == 'E')) { const int MAX_EXP = (1 << 30); // even playing ground char exponentSign = '\0'; i++; if (i < source.Length && (source[i] == '-' || source[i] == '+')) { exponentSign = source[i]; i++; } int firstExponent = i; int lastExponent = i; while (i < source.Length && source[i] >= '0' && source[i] <= '9') lastExponent = ++i; int exponentMagnitude = 0; if (int.TryParse(source.Substring(firstExponent, lastExponent - firstExponent), out exponentMagnitude) && exponentMagnitude <= MAX_EXP) { if (exponentSign == '-') { exponent -= exponentMagnitude; } else { exponent += exponentMagnitude; } } else { exponent = exponentSign == '-' ? -MAX_EXP : MAX_EXP; } } result.Exponent = exponent; return result; } } private enum Status { OK, NoDigits, Underflow, Overflow } /// <summary> /// Convert a DecimalFloatingPointString to the bits of the given floating-point type. /// </summary> private static Status ConvertDecimalToFloatingPointBits(DecimalFloatingPointString data, FloatingPointType type, out ulong result) { if (data.Mantissa.Length == 0) { result = type.Zero; return Status.NoDigits; } // To generate an N bit mantissa we require N + 1 bits of precision. The // extra bit is used to correctly round the mantissa (if there are fewer bits // than this available, then that's totally okay; in that case we use what we // have and we don't need to round). uint requiredBitsOfPrecision = (uint)type.NormalMantissaBits + 1; // The input is of the form 0.Mantissa x 10^Exponent, where 'Mantissa' are // the decimal digits of the mantissa and 'Exponent' is the decimal exponent. // We decompose the mantissa into two parts: an integer part and a fractional // part. If the exponent is positive, then the integer part consists of the // first 'exponent' digits, or all present digits if there are fewer digits. // If the exponent is zero or negative, then the integer part is empty. In // either case, the remaining digits form the fractional part of the mantissa. uint positiveExponent = (uint)Math.Max(0, data.Exponent); uint integerDigitsPresent = Math.Min(positiveExponent, data.MantissaCount); uint integerDigitsMissing = positiveExponent - integerDigitsPresent; uint integerFirstIndex = 0; uint integerLastIndex = integerDigitsPresent; uint fractionalFirstIndex = integerLastIndex; uint fractionalLastIndex = data.MantissaCount; uint fractionalDigitsPresent = fractionalLastIndex - fractionalFirstIndex; // First, we accumulate the integer part of the mantissa into a big_integer: BigInteger integerValue = AccumulateDecimalDigitsIntoBigInteger(data, integerFirstIndex, integerLastIndex); if (integerDigitsMissing > 0) { if (integerDigitsMissing > type.OverflowDecimalExponent) { result = type.Infinity; return Status.Overflow; } MultiplyByPowerOfTen(ref integerValue, integerDigitsMissing); } // At this point, the integer_value contains the value of the integer part // of the mantissa. If either [1] this number has more than the required // number of bits of precision or [2] the mantissa has no fractional part, // then we can assemble the result immediately: byte[] integerValueAsBytes; uint integerBitsOfPrecision = CountSignificantBits(integerValue, out integerValueAsBytes); if (integerBitsOfPrecision >= requiredBitsOfPrecision || fractionalDigitsPresent == 0) { return ConvertBigIntegerToFloatingPointBits( integerValueAsBytes, integerBitsOfPrecision, fractionalDigitsPresent != 0, type, out result); } // Otherwise, we did not get enough bits of precision from the integer part, // and the mantissa has a fractional part. We parse the fractional part of // the mantissa to obtain more bits of precision. To do this, we convert // the fractional part into an actual fraction N/M, where the numerator N is // computed from the digits of the fractional part, and the denominator M is // computed as the power of 10 such that N/M is equal to the value of the // fractional part of the mantissa. uint fractionalDenominatorExponent = data.Exponent < 0 ? fractionalDigitsPresent + (uint)-data.Exponent : fractionalDigitsPresent; if (integerBitsOfPrecision == 0 && (fractionalDenominatorExponent - (int)data.MantissaCount) > type.OverflowDecimalExponent) { // If there were any digits in the integer part, it is impossible to // underflow (because the exponent cannot possibly be small enough), // so if we underflow here it is a true underflow and we return zero. result = type.Zero; return Status.Underflow; } BigInteger fractionalNumerator = AccumulateDecimalDigitsIntoBigInteger(data, fractionalFirstIndex, fractionalLastIndex); Debug.Assert(!fractionalNumerator.IsZero); BigInteger fractionalDenominator = s_bigOne; MultiplyByPowerOfTen(ref fractionalDenominator, fractionalDenominatorExponent); // Because we are using only the fractional part of the mantissa here, the // numerator is guaranteed to be smaller than the denominator. We normalize // the fraction such that the most significant bit of the numerator is in // the same position as the most significant bit in the denominator. This // ensures that when we later shift the numerator N bits to the left, we // will produce N bits of precision. uint fractionalNumeratorBits = CountSignificantBits(fractionalNumerator); uint fractionalDenominatorBits = CountSignificantBits(fractionalDenominator); uint fractionalShift = fractionalDenominatorBits > fractionalNumeratorBits ? fractionalDenominatorBits - fractionalNumeratorBits : 0; if (fractionalShift > 0) { ShiftLeft(ref fractionalNumerator, fractionalShift); } uint requiredFractionalBitsOfPrecision = requiredBitsOfPrecision - integerBitsOfPrecision; uint remainingBitsOfPrecisionRequired = requiredFractionalBitsOfPrecision; if (integerBitsOfPrecision > 0) { // If the fractional part of the mantissa provides no bits of precision // and cannot affect rounding, we can just take whatever bits we got from // the integer part of the mantissa. This is the case for numbers like // 5.0000000000000000000001, where the significant digits of the fractional // part start so far to the right that they do not affect the floating // point representation. // // If the fractional shift is exactly equal to the number of bits of // precision that we require, then no fractional bits will be part of the // result, but the result may affect rounding. This is e.g. the case for // large, odd integers with a fractional part greater than or equal to .5. // Thus, we need to do the division to correctly round the result. if (fractionalShift > remainingBitsOfPrecisionRequired) { return ConvertBigIntegerToFloatingPointBits( integerValueAsBytes, integerBitsOfPrecision, fractionalDigitsPresent != 0, type, out result); } remainingBitsOfPrecisionRequired -= fractionalShift; } // If there was no integer part of the mantissa, we will need to compute the // exponent from the fractional part. The fractional exponent is the power // of two by which we must multiply the fractional part to move it into the // range [1.0, 2.0). This will either be the same as the shift we computed // earlier, or one greater than that shift: uint fractionalExponent = fractionalNumerator < fractionalDenominator ? fractionalShift + 1 : fractionalShift; ShiftLeft(ref fractionalNumerator, remainingBitsOfPrecisionRequired); BigInteger fractionalRemainder; BigInteger bigFractionalMantissa = BigInteger.DivRem(fractionalNumerator, fractionalDenominator, out fractionalRemainder); ulong fractionalMantissa = (ulong)bigFractionalMantissa; bool hasZeroTail = fractionalRemainder.IsZero; // We may have produced more bits of precision than were required. Check, // and remove any "extra" bits: uint fractionalMantissaBits = CountSignificantBits(fractionalMantissa); if (fractionalMantissaBits > requiredFractionalBitsOfPrecision) { int shift = (int)(fractionalMantissaBits - requiredFractionalBitsOfPrecision); hasZeroTail = hasZeroTail && (fractionalMantissa & ((1UL << shift) - 1)) == 0; fractionalMantissa >>= shift; } // Compose the mantissa from the integer and fractional parts: Debug.Assert(integerBitsOfPrecision < 60); // we can use BigInteger's built-in conversion ulong integerMantissa = (ulong)integerValue; ulong completeMantissa = (integerMantissa << (int)requiredFractionalBitsOfPrecision) + fractionalMantissa; // Compute the final exponent: // * If the mantissa had an integer part, then the exponent is one less than // the number of bits we obtained from the integer part. (It's one less // because we are converting to the form 1.11111, with one 1 to the left // of the decimal point.) // * If the mantissa had no integer part, then the exponent is the fractional // exponent that we computed. // Then, in both cases, we subtract an additional one from the exponent, to // account for the fact that we've generated an extra bit of precision, for // use in rounding. int finalExponent = integerBitsOfPrecision > 0 ? (int)integerBitsOfPrecision - 2 : -(int)(fractionalExponent) - 1; return type.AssembleFloatingPointValue(completeMantissa, finalExponent, hasZeroTail, out result); } /// <summary> /// This function is part of the fast track for integer floating point strings. /// It takes an integer stored as an array of bytes (lsb first) and converts the value into its FloatingType /// representation, storing the bits into "result". If the value is not /// representable, +/-infinity is stored and overflow is reported (since this /// function only deals with integers, underflow is impossible). /// </summary> /// <param name="integerValueAsBytes">the bits of the integer, least significant bits first</param> /// <param name="integerBitsOfPrecision">the number of bits of precision in integerValueAsBytes</param> /// <param name="hasNonzeroFractionalPart">whether there are nonzero digits after the decimal</param> /// <param name="type">the kind of real number to build</param> /// <param name="result">the result</param> /// <returns>An indicator of the kind of result</returns> private static Status ConvertBigIntegerToFloatingPointBits(byte[] integerValueAsBytes, uint integerBitsOfPrecision, bool hasNonzeroFractionalPart, FloatingPointType type, out ulong result) { int baseExponent = type.DenormalMantissaBits; int exponent; ulong mantissa; bool has_zero_tail = !hasNonzeroFractionalPart; int topElementIndex = ((int)integerBitsOfPrecision - 1) / 8; // The high-order byte of integerValueAsBytes might not have a full eight bits. However, // since the data are stored in quanta of 8 bits, and we really only need around 54 // bits of mantissa for a double (and fewer for a float), we can just assemble data // from the eight high-order bytes and we will get between 59 and 64 bits, which is more // than enough. int bottomElementIndex = Math.Max(0, topElementIndex - (64 / 8) + 1); exponent = baseExponent + bottomElementIndex * 8; mantissa = 0; for (int i = (int)topElementIndex; i >= bottomElementIndex; i--) { mantissa <<= 8; mantissa |= integerValueAsBytes[i]; } for (int i = bottomElementIndex - 1; has_zero_tail && i >= 0; i--) { if (integerValueAsBytes[i] != 0) has_zero_tail = false; } return type.AssembleFloatingPointValue(mantissa, exponent, has_zero_tail, out result); } /// <summary> /// Parse a sequence of digits into a BigInteger. /// </summary> /// <param name="data">The DecimalFloatingPointString containing the digits in its Mantissa</param> /// <param name="integer_first_index">The index of the first digit to convert</param> /// <param name="integer_last_index">The index just past the last digit to convert</param> /// <returns>The BigInteger result</returns> private static BigInteger AccumulateDecimalDigitsIntoBigInteger(DecimalFloatingPointString data, uint integer_first_index, uint integer_last_index) { if (integer_first_index == integer_last_index) return s_bigZero; var valueString = data.Mantissa.Substring((int)integer_first_index, (int)(integer_last_index - integer_first_index)); return BigInteger.Parse(valueString); } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(ulong data) { uint result = 0; while (data != 0) { data >>= 1; result++; } return result; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(byte data) { uint result = 0; while (data != 0) { data >>= 1; result++; } return result; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(BigInteger data, out byte[] dataBytes) { if (data.IsZero) { dataBytes = new byte[1]; return 0; } dataBytes = data.ToByteArray(); // the bits of the BigInteger, least significant bits first for (int i = dataBytes.Length - 1; i >= 0; i--) { var v = dataBytes[i]; if (v != 0) return 8 * (uint)i + CountSignificantBits(v); } return 0; } /// <summary> /// Return the number of significant bits set. /// </summary> private static uint CountSignificantBits(BigInteger data) { byte[] dataBytes; return CountSignificantBits(data, out dataBytes); } /// <summary> /// Computes value / 2^shift, then rounds the result according to the current /// rounding mode. By the time we call this function, we will already have /// discarded most digits. The caller must pass true for has_zero_tail if /// all discarded bits were zeroes. /// </summary> /// <param name="value">The value to shift</param> /// <param name="shift">The amount of shift</param> /// <param name="hasZeroTail">Whether there are any less significant nonzero bits in the value</param> /// <returns></returns> private static ulong RightShiftWithRounding(ulong value, int shift, bool hasZeroTail) { // If we'd need to shift further than it is possible to shift, the answer // is always zero: if (shift >= 64) return 0; ulong extraBitsMask = (1UL << (shift - 1)) - 1; ulong roundBitMask = (1UL << (shift - 1)); ulong lsbBitMask = 1UL << shift; bool lsbBit = (value & lsbBitMask) != 0; bool roundBit = (value & roundBitMask) != 0; bool hasTailBits = !hasZeroTail || (value & extraBitsMask) != 0; return (value >> shift) + (ShouldRoundUp(lsbBit: lsbBit, roundBit: roundBit, hasTailBits: hasTailBits) ? 1UL : 0); } /// <summary> /// Determines whether a mantissa should be rounded up in the /// round-to-nearest-ties-to-even mode given [1] the value of the least /// significant bit of the mantissa, [2] the value of the next bit after /// the least significant bit (the "round" bit) and [3] whether any /// trailing bits after the round bit are set. /// /// The mantissa is treated as an unsigned integer magnitude. /// /// For this function, "round up" is defined as "increase the magnitude" of the /// mantissa. /// </summary> /// <param name="lsbBit">the least-significant bit of the representable value</param> /// <param name="roundBit">the bit following the least-significant bit</param> /// <param name="hasTailBits">true if there are any (less significant) bits set following roundBit</param> /// <returns></returns> private static bool ShouldRoundUp( bool lsbBit, bool roundBit, bool hasTailBits) { // If there are insignificant set bits, we need to round to the // nearest; there are two cases: // we round up if either [1] the value is slightly greater than the midpoint // between two exactly representable values or [2] the value is exactly the // midpoint between two exactly representable values and the greater of the // two is even (this is "round-to-even"). return roundBit && (hasTailBits || lsbBit); } /// <summary> /// Multiply a BigInteger by the given power of two. /// </summary> /// <param name="number">The BigInteger to multiply by a power of two and replace with the product</param> /// <param name="shift">The power of two to multiply it by</param> private static void ShiftLeft(ref BigInteger number, uint shift) { var powerOfTwo = BigInteger.Pow(s_bigTwo, (int)shift); number = number * powerOfTwo; } /// <summary> /// Multiply a BigInteger by the given power of ten. /// </summary> /// <param name="number">The BigInteger to multiply by a power of ten and replace with the product</param> /// <param name="power">The power of ten to multiply it by</param> private static void MultiplyByPowerOfTen(ref BigInteger number, uint power) { var powerOfTen = BigInteger.Pow(s_bigTen, (int)power); number = number * powerOfTen; } /// <summary> /// Convert a float value to the bits of its representation /// </summary> private static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } /// <summary> /// Convert the bits of its representation to a float /// </summary> private static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } /// <summary> /// A union used to convert between a float and the bits of its representation /// </summary> [StructLayout(LayoutKind.Explicit)] private struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/Diagnostics/AbstractDiagnosticsAdornmentTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { internal abstract class AbstractDiagnosticsAdornmentTaggerProvider<TTag> : AbstractDiagnosticsTaggerProvider<TTag> where TTag : class, ITag { public AbstractDiagnosticsAdornmentTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorSquiggles)) { } protected internal sealed override bool IsEnabled => true; protected internal sealed override ITagSpan<TTag>? CreateTagSpan( Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data) { var errorTag = CreateTag(workspace, data); if (errorTag == null) { return null; } // Live update squiggles have to be at least 1 character long. var minimumLength = isLiveUpdate ? 1 : 0; var adjustedSpan = AdjustSnapshotSpan(span, minimumLength); if (adjustedSpan.Length == 0) { return null; } return new TagSpan<TTag>(adjustedSpan, errorTag); } protected static object CreateToolTipContent(Workspace workspace, DiagnosticData diagnostic) { Action? navigationAction = null; string? tooltip = null; if (workspace is object && diagnostic.HelpLink is { } helpLink && Uri.TryCreate(helpLink, UriKind.Absolute, out var helpLinkUri)) { navigationAction = new QuickInfoHyperLink(workspace, helpLinkUri).NavigationAction; tooltip = helpLink; } var diagnosticIdTextRun = navigationAction is null ? new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id) : new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id, navigationAction, tooltip); return new ContainerElement( ContainerElementStyle.Wrapped, new ClassifiedTextElement( diagnosticIdTextRun, new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"), new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Message))); } protected virtual SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength) => AdjustSnapshotSpan(span, minimumLength, int.MaxValue); protected static SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength, int maximumLength) { var snapshot = span.Snapshot; // new length var length = Math.Min(Math.Max(span.Length, minimumLength), maximumLength); // make sure start + length is smaller than snapshot.Length and start is >= 0 var start = Math.Max(0, Math.Min(span.Start, snapshot.Length - length)); // make sure length is smaller than snapshot.Length which can happen if start == 0 return new SnapshotSpan(snapshot, start, Math.Min(start + length, snapshot.Length) - start); } protected abstract TTag? CreateTag(Workspace workspace, DiagnosticData diagnostic); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { internal abstract class AbstractDiagnosticsAdornmentTaggerProvider<TTag> : AbstractDiagnosticsTaggerProvider<TTag> where TTag : class, ITag { public AbstractDiagnosticsAdornmentTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorSquiggles)) { } protected internal sealed override bool IsEnabled => true; protected internal sealed override ITagSpan<TTag>? CreateTagSpan( Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data) { var errorTag = CreateTag(workspace, data); if (errorTag == null) { return null; } // Live update squiggles have to be at least 1 character long. var minimumLength = isLiveUpdate ? 1 : 0; var adjustedSpan = AdjustSnapshotSpan(span, minimumLength); if (adjustedSpan.Length == 0) { return null; } return new TagSpan<TTag>(adjustedSpan, errorTag); } protected static object CreateToolTipContent(Workspace workspace, DiagnosticData diagnostic) { Action? navigationAction = null; string? tooltip = null; if (workspace is object && diagnostic.HelpLink is { } helpLink && Uri.TryCreate(helpLink, UriKind.Absolute, out var helpLinkUri)) { navigationAction = new QuickInfoHyperLink(workspace, helpLinkUri).NavigationAction; tooltip = helpLink; } var diagnosticIdTextRun = navigationAction is null ? new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id) : new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id, navigationAction, tooltip); return new ContainerElement( ContainerElementStyle.Wrapped, new ClassifiedTextElement( diagnosticIdTextRun, new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"), new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Message))); } protected virtual SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength) => AdjustSnapshotSpan(span, minimumLength, int.MaxValue); protected static SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength, int maximumLength) { var snapshot = span.Snapshot; // new length var length = Math.Min(Math.Max(span.Length, minimumLength), maximumLength); // make sure start + length is smaller than snapshot.Length and start is >= 0 var start = Math.Max(0, Math.Min(span.Start, snapshot.Length - length)); // make sure length is smaller than snapshot.Length which can happen if start == 0 return new SnapshotSpan(snapshot, start, Math.Min(start + length, snapshot.Length) - start); } protected abstract TTag? CreateTag(Workspace workspace, DiagnosticData diagnostic); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EELocalConstantSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EELocalConstantSymbol : EELocalSymbolBase { private readonly MethodSymbol _method; private readonly string _name; private readonly TypeWithAnnotations _type; private readonly ConstantValue _value; public EELocalConstantSymbol( MethodSymbol method, string name, TypeSymbol type, ConstantValue value) : this(method, name, TypeWithAnnotations.Create(type), value) { } public EELocalConstantSymbol( MethodSymbol method, string name, TypeWithAnnotations type, ConstantValue value) { _method = method; _name = name; _type = type; _value = value; } internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap) { var type = typeMap.SubstituteType(_type); return new EELocalConstantSymbol(method, _name, type, _value); } public override string Name { get { return _name; } } internal override LocalDeclarationKind DeclarationKind { get { return LocalDeclarationKind.Constant; } } internal override SyntaxToken IdentifierToken { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { return _method; } } public override TypeWithAnnotations TypeWithAnnotations { get { return _type; } } internal override bool IsPinned { get { return false; } } internal override bool IsCompilerGenerated { get { return false; } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) { if (diagnostics != null && _value.IsBad) { diagnostics.Add(ErrorCode.ERR_BadPdbData, Location.None, Name); } return _value; } public override RefKind RefKind { get { return RefKind.None; } } public override ImmutableArray<Location> Locations { get { return NoLocations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EELocalConstantSymbol : EELocalSymbolBase { private readonly MethodSymbol _method; private readonly string _name; private readonly TypeWithAnnotations _type; private readonly ConstantValue _value; public EELocalConstantSymbol( MethodSymbol method, string name, TypeSymbol type, ConstantValue value) : this(method, name, TypeWithAnnotations.Create(type), value) { } public EELocalConstantSymbol( MethodSymbol method, string name, TypeWithAnnotations type, ConstantValue value) { _method = method; _name = name; _type = type; _value = value; } internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap) { var type = typeMap.SubstituteType(_type); return new EELocalConstantSymbol(method, _name, type, _value); } public override string Name { get { return _name; } } internal override LocalDeclarationKind DeclarationKind { get { return LocalDeclarationKind.Constant; } } internal override SyntaxToken IdentifierToken { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { return _method; } } public override TypeWithAnnotations TypeWithAnnotations { get { return _type; } } internal override bool IsPinned { get { return false; } } internal override bool IsCompilerGenerated { get { return false; } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) { if (diagnostics != null && _value.IsBad) { diagnostics.Add(ErrorCode.ERR_BadPdbData, Location.None, Name); } return _value; } public override RefKind RefKind { get { return RefKind.None; } } public override ImmutableArray<Location> Locations { get { return NoLocations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/EventFieldDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public event EventArgs $$goo }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}public event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public event EventArgs $$goo }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Goo] |}public event EventArgs $$goo|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/GoToDefinition/GoToDefinitionCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToDefinition)] internal class GoToDefinitionCommandHandler : ICommandHandler<GoToDefinitionCommandArgs> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GoToDefinitionCommandHandler() { } public string DisplayName => EditorFeaturesResources.Go_to_Definition; private static (Document, IGoToDefinitionService) GetDocumentAndService(ITextSnapshot snapshot) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); return (document, document?.GetLanguageService<IGoToDefinitionService>()); } public CommandState GetCommandState(GoToDefinitionCommandArgs args) { var (_, service) = GetDocumentAndService(args.SubjectBuffer.CurrentSnapshot); return service != null ? CommandState.Available : CommandState.Unspecified; } public bool ExecuteCommand(GoToDefinitionCommandArgs args, CommandExecutionContext context) { var subjectBuffer = args.SubjectBuffer; var (document, service) = GetDocumentAndService(subjectBuffer.CurrentSnapshot); // In Live Share, typescript exports a gotodefinition service that returns no results and prevents the LSP client // from handling the request. So prevent the local service from handling goto def commands in the remote workspace. // This can be removed once typescript implements LSP support for goto def. if (service != null && !subjectBuffer.IsInLspEditorContext()) { var caretPos = args.TextView.GetCaretPoint(subjectBuffer); if (caretPos.HasValue && TryExecuteCommand(document, caretPos.Value, service, context)) { return true; } } return false; } // Internal for testing purposes only. internal static bool TryExecuteCommand(ITextSnapshot snapshot, int caretPosition, CommandExecutionContext context) => TryExecuteCommand(snapshot.GetOpenDocumentInCurrentContextWithChanges(), caretPosition, context); internal static bool TryExecuteCommand(Document document, int caretPosition, CommandExecutionContext context) => TryExecuteCommand(document, caretPosition, document.GetLanguageService<IGoToDefinitionService>(), context); internal static bool TryExecuteCommand(Document document, int caretPosition, IGoToDefinitionService goToDefinitionService, CommandExecutionContext context) { string errorMessage = null; using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Navigating_to_definition)) { if (goToDefinitionService != null && goToDefinitionService.TryGoToDefinition(document, caretPosition, context.OperationContext.UserCancellationToken)) { return true; } errorMessage = EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret; } if (errorMessage != null) { // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var workspace = document.Project.Solution.Workspace; var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(errorMessage, title: EditorFeaturesResources.Go_to_Definition, severity: NotificationSeverity.Information); } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToDefinition)] internal class GoToDefinitionCommandHandler : ICommandHandler<GoToDefinitionCommandArgs> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GoToDefinitionCommandHandler() { } public string DisplayName => EditorFeaturesResources.Go_to_Definition; private static (Document, IGoToDefinitionService) GetDocumentAndService(ITextSnapshot snapshot) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); return (document, document?.GetLanguageService<IGoToDefinitionService>()); } public CommandState GetCommandState(GoToDefinitionCommandArgs args) { var (_, service) = GetDocumentAndService(args.SubjectBuffer.CurrentSnapshot); return service != null ? CommandState.Available : CommandState.Unspecified; } public bool ExecuteCommand(GoToDefinitionCommandArgs args, CommandExecutionContext context) { var subjectBuffer = args.SubjectBuffer; var (document, service) = GetDocumentAndService(subjectBuffer.CurrentSnapshot); // In Live Share, typescript exports a gotodefinition service that returns no results and prevents the LSP client // from handling the request. So prevent the local service from handling goto def commands in the remote workspace. // This can be removed once typescript implements LSP support for goto def. if (service != null && !subjectBuffer.IsInLspEditorContext()) { var caretPos = args.TextView.GetCaretPoint(subjectBuffer); if (caretPos.HasValue && TryExecuteCommand(document, caretPos.Value, service, context)) { return true; } } return false; } // Internal for testing purposes only. internal static bool TryExecuteCommand(ITextSnapshot snapshot, int caretPosition, CommandExecutionContext context) => TryExecuteCommand(snapshot.GetOpenDocumentInCurrentContextWithChanges(), caretPosition, context); internal static bool TryExecuteCommand(Document document, int caretPosition, CommandExecutionContext context) => TryExecuteCommand(document, caretPosition, document.GetLanguageService<IGoToDefinitionService>(), context); internal static bool TryExecuteCommand(Document document, int caretPosition, IGoToDefinitionService goToDefinitionService, CommandExecutionContext context) { string errorMessage = null; using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Navigating_to_definition)) { if (goToDefinitionService != null && goToDefinitionService.TryGoToDefinition(document, caretPosition, context.OperationContext.UserCancellationToken)) { return true; } errorMessage = EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret; } if (errorMessage != null) { // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var workspace = document.Project.Solution.Workspace; var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(errorMessage, title: EditorFeaturesResources.Go_to_Definition, severity: NotificationSeverity.Information); } return true; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/Razor/IRazorDocumentPropertiesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable annotations namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDocumentPropertiesService { /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built. /// </summary> public bool DesignTimeOnly { get; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public string? DiagnosticsLspClientName { 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. #nullable enable annotations namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDocumentPropertiesService { /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built. /// </summary> public bool DesignTimeOnly { get; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public string? DiagnosticsLspClientName { get; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/CodeActions/InlineTemporary/InlineTemporaryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.InlineTemporary { public class InlineTemporaryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new InlineTemporaryCodeRefactoringProvider(); private async Task TestFixOneAsync(string initial, string expected) => await TestInRegularAndScript1Async(GetTreeText(initial), GetTreeText(expected)); private static string GetTreeText(string initial) { return @"class C { void F() " + initial + @" }"; } private static SyntaxNode GetNodeToFix(dynamic initialRoot, int declaratorIndex) => initialRoot.Members[0].Members[0].Body.Statements[0].Declaration.Variables[declaratorIndex]; private static SyntaxNode GetFixedNode(dynamic fixedRoot) => fixedRoot.Members[0].Members[0].BodyOpt; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer1() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer2() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = ; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnSecondWithNoInitializer() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 42, [||]y; System.Console.WriteLine(y); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnField() { await TestMissingInRegularAndScriptAsync( @"class C { int [||]x = 42; void M() { System.Console.WriteLine(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WithRefInitializer1() { await TestMissingInRegularAndScriptAsync( @"class C { ref int M() { int[] arr = new[] { 1, 2, 3 }; ref int [||]x = ref arr[2]; return ref x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task SingleStatement() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 27; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_First() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 0, y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Second() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, [||]y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Last() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, y = 1, [||]z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping1() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping2() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping3() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping4() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping5() { var code = @" using System.Linq; class C { static void Main() { var @where[||] = 0; var q = from e in """" let a = new { @where } select a; } }"; var expected = @" using System.Linq; class C { static void Main() { var q = from e in """" let a = new { @where = 0 } select a; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Call() { var code = @" using System; class C { public void M() { int [||]x = 1 + 1; x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1 + 1).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoChange() { var code = @" using System; class C { public void M() { double [||]x = 3; x.ToString(); } }"; var expected = @" using System; class C { public void M() { ((double)3).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoConversion() { await TestFixOneAsync( @"{ int [||]x = 3; x.ToString(); }", @"{ 3.ToString(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentOverload() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { double [||]x = 3; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((double)3); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(""hi""); } } ", @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { ((Base)new Derived()).M(""hi""); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_SameMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(3); } } ", @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { new Derived().M(3); } } "); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] public async Task Conversion_NonTargetTypedConditionalExpression(LanguageVersion languageVersion) { await TestInRegularAndScriptAsync( @" class C { void F() { int? [||]x = 42; var y = true ? x : null; } } ", @" class C { void F() { var y = true ? (int?)42 : null; } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [InlineData(LanguageVersion.CSharp8, "(int?)42")] [InlineData(LanguageVersion.CSharp9, "42")] // In C# 9, target-typed conditionals makes this work public async Task Conversion_TargetTypedConditionalExpression(LanguageVersion languageVersion, string expectedSubstitution) { await TestInRegularAndScriptAsync( @" class C { void F() { int? [||]x = 42; int? y = true ? x : null; } } ", @" class C { void F() { int? y = true ? " + expectedSubstitution + @" : null; } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NoCastOnVar() { await TestFixOneAsync( @"{ var [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoubleAssignment() { var code = @" class C { void M() { int [||]x = x = 1; int y = x; } }"; var expected = @" class C { void M() { int y = 1; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAnonymousType1() { await TestFixOneAsync( @"{ int [||]x = 42; var a = new { x }; }", @"{ var a = new { x = 42 }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestParenthesizedAtReference_Case3() { await TestFixOneAsync( @"{ int [||]x = 1 + 1; int y = x * 2; }", @"{ int y = (1 + 1) * 2; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontBreakOverloadResolution_Case5() { var code = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { object [||]x = 1 + 1; Goo(x); } }"; var expected = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { Goo((object)(1 + 1)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontTouchUnrelatedBlocks() { var code = @" class C { void M() { int [||]x = 1; { Unrelated(); } Goo(x); } }"; var expected = @" class C { void M() { { Unrelated(); } Goo(1); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLambdaParenthesizeAndCast_Case7() { var code = @" class C { void M() { System.Func<int> [||]x = () => 1; int y = x(); } }"; var expected = @" class C { void M() { int y = ((System.Func<int>)(() => 1))(); } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity1() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094"), WorkItem(541462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity2() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; object [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity3() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (int)1; F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (int)1)); } int f = 0; }"); } [WorkItem(544924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544924")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity4() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1+2); Bar(x < x, x > y); } static void Bar(object a, object b) { } }", @" class Program { static void Main() { int x = 2; Bar(x < x, (x > (1 + 2))); } static void Bar(object a, object b) { } }"); } [WorkItem(544613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544613")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity5() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1 + 2); var z = new[] { x < x, x > y }; } }", @" class Program { static void Main() { int x = 2; var z = new[] { x < x, (x > (1 + 2)) }; } }"); } [WorkItem(538131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538131")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer() { await TestFixOneAsync( @"{ int[] [||]x = { 3, 4, 5 }; int a = Array.IndexOf(x, 3); }", @"{ int a = Array.IndexOf(new int[] { 3, 4, 5 }, 3); }"); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer2() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer3() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter1() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(ref x); Goo(x); } void Goo(int x) { } void Goo(ref int x) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(ref {|Conflict:x|}); Goo(0); } void Goo(int x) { } void Goo(ref int x) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter2() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(x, ref x); } void Goo(int x, ref int y) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(0, ref {|Conflict:x|}); } void Goo(int x, ref int y) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i = 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} = 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression1() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i += 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} += 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression2() { var initial = @"using System; class C { static int x; static void M() { int [||]x = (x = 0) + (x += 1); int y = x; } }"; var expected = @"using System; class C { static int x; static void M() { int x = ({|Conflict:x|} = 0) + ({|Conflict:x|} += 1); int y = 0 + ({|Conflict:x|} += 1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_SubtractAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i -= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} -= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_MultiplyAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i *= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} *= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_DivideAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i /= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} /= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ModuloAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i %= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} %= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AndAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i &= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} &= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_OrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i |= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} |= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ExclusiveOrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i ^= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} ^= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_LeftShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i <<= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} <<= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RightShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i >>= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} >>= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i++; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}++; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; ++i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; ++{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i--; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}--; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; --i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; --{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddressOfExpression() { var initial = @" class C { unsafe void M() { int x = 0; var y[||] = &x; var z = &y; } }"; var expected = @" class C { unsafe void M() { int x = 0; var y = &x; var z = &{|Conflict:y|}; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545342")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_UsedBeforeDeclaration() { var initial = @"class Program { static void Main(string[] args) { var x = y; var y[||] = 45; } }"; var expected = @"class Program { static void Main(string[] args) { var x = {|Conflict:y|}; var y = 45; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor1() { await TestFixOneAsync(@" { int [||]x = 1, #if true y, #endif z; int a = x; }", @" { int #if true y, #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor2() { await TestFixOneAsync(@" { int y, #if true [||]x = 1, #endif z; int a = x; }", @" { int y, #if true #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor3() { await TestFixOneAsync(@" { int y, #if true z, #endif [||]x = 1; int a = x; }", @" { int y, #if true z #endif ; int a = 1; }"); } [WorkItem(540164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540164")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TriviaOnArrayInitializer() { var initial = @"class C { void M() { int[] [||]a = /**/{ 1 }; Goo(a); } }"; var expected = @"class C { void M() { Goo(new int[]/**/{ 1 }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator1() { var initial = @"class C { void M() { int [||]i = 1, j = 2, k = 3; System.Console.Write(i); } }"; var expected = @"class C { void M() { int j = 2, k = 3; System.Console.Write(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator2() { var initial = @"class C { void M() { int i = 1, [||]j = 2, k = 3; System.Console.Write(j); } }"; var expected = @"class C { void M() { int i = 1, k = 3; System.Console.Write(2); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator3() { var initial = @"class C { void M() { int i = 1, j = 2, [||]k = 3; System.Console.Write(k); } }"; var expected = @"class C { void M() { int i = 1, j = 2; System.Console.Write(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540186")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatAnonymousTypeMember() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(6356, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineToAnonymousTypeProperty() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x = x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(528075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528075")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoDelegateInvocation() { var initial = @"using System; class Program { static void Main(string[] args) { Action<string[]> [||]del = Main; del(null); } }"; var expected = @"using System; class Program { static void Main(string[] args) { ((Action<string[]>)Main)(null); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineAnonymousMethodIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = delegate { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)delegate { } ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineLambdaIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = () => { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)(() => { }) ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation1() { var initial = @"using System; class A { static void Main() { long x[||] = 1; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { object z = (long)1; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation2() { var initial = @"using System; class A { static void Main() { int y = 1; long x[||] = y; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { int y = 1; object z = (long)y; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation3() { var initial = @"using System; class A { static void Main() { byte x[||] = 1; object z = x; Console.WriteLine((byte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (byte)1; Console.WriteLine((byte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation4() { var initial = @"using System; class A { static void Main() { sbyte x[||] = 1; object z = x; Console.WriteLine((sbyte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (sbyte)1; Console.WriteLine((sbyte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation5() { var initial = @"using System; class A { static void Main() { short x[||] = 1; object z = x; Console.WriteLine((short)z); } }"; var expected = @"using System; class A { static void Main() { object z = (short)1; Console.WriteLine((short)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestPreprocessor() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { #if true int [||]i = 10; //print Console.Write(i); #endif } }", @"class Program { static void Main(string[] args) { #if true //print Console.Write(10); #endif } }"); } [WorkItem(540277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540277")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestFormatting() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 5; int j = 110; Console.Write(i + j); } }", @"class Program { static void Main(string[] args) { int j = 110; Console.Write(5 + j); } }"); } [WorkItem(541694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541694")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSwitchSection() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { switch (10) { default: int i[||] = 10; Console.WriteLine(i); break; } } }", @"using System; class C { void M() { switch (10) { default: Console.WriteLine(10); break; } } }"); } [WorkItem(542647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded1() { await TestInRegularAndScriptAsync( @" using System; class C { static Action X; static void M() { var [||]y = (X); y(); } } ", @" using System; class C { static Action X; static void M() { X(); } } "); } [WorkItem(545619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545619")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Action x = Console.WriteLine; Action y[||] = x; y(); } } ", @" using System; class Program { static void Main() { Action x = Console.WriteLine; x(); } } "); } [WorkItem(542656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542656")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary1() { await TestInRegularAndScriptAsync( @"using System; using System.Collections; using System.Linq; class A { static void Main() { var [||]q = from x in """" select x; if (q is IEnumerable) { } } }", @"using System; using System.Collections; using System.Linq; class A { static void Main() { if ((from x in """" select x) is IEnumerable) { } } }"); } [WorkItem(544626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544626")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Action<string> f[||] = Goo<string>; Action<string> g = null; var h = f + g; } static void Goo<T>(T y) { } }", @" using System; class C { static void Main() { Action<string> g = null; var h = Goo + g; } static void Goo<T>(T y) { } }"); } [WorkItem(544415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544415")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = (Int32)p; } }", @" using System; unsafe class C { static void M() { int x; var i = (Int32)(&x); } }"); } [WorkItem(544922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544922")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = p->ToString(); } }", @" using System; unsafe class C { static void M() { int x; var i = (&x)->ToString(); } }"); } [WorkItem(544921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544921")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int* x = null; int p[||] = *x; var i = (Int64)p; } }", @" using System; unsafe class C { static void M() { int* x = null; var i = (Int64)(*x); } }"); } [WorkItem(544614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544614")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int** x = null; int* p[||] = *x; var i = p[1].ToString(); } }", @" using System; unsafe class C { static void M() { int** x = null; var i = (*x)[1].ToString(); } }"); } [WorkItem(544563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544563")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInlineStackAlloc() { await TestMissingInRegularAndScriptAsync( @"using System; unsafe class C { static void M() { int* values[||] = stackalloc int[20]; int* copy = values; int* p = &values[1]; int* q = &values[15]; } }"); } [WorkItem(543744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempLambdaExpressionCastingError() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int?,int?> [||]lam = (int? s) => { return s; }; Console.WriteLine(lam); } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine((int? s) => { return s; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForNull() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { string [||]x = null; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((string)null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded1() { await TestInRegularAndScriptAsync( @" class C { void M() { long x[||] = 1; System.IComparable<long> y = x; } }", @" class C { void M() { System.IComparable<long> y = (long)1; } }"); } [WorkItem(545161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545161")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Goo(x => { int [||]y = x[0]; x[1] = y; }); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }", @" using System; class C { static void Main() { Goo((Action<int[]>)(x => { x[1] = x[0]; })); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }"); } [WorkItem(544612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544612")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoBracketedList() { await TestInRegularAndScriptAsync( @" class C { void M() { var c = new C(); int x[||] = 1; c[x] = 2; } int this[object x] { set { } } }", @" class C { void M() { var c = new C(); c[1] = 2; } int this[object x] { set { } } }"); } [WorkItem(542648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542648")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAfterCastIfNeeded() { await TestAsync( @" using System; enum E { } class Program { static void Main() { E x[||] = (global::E) -1; object y = x; } }", @" using System; enum E { } class Program { static void Main() { object y = (global::E)-1; } }", parseOptions: null); } [WorkItem(544635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544635")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForEnumZeroIfBoxed() { await TestAsync( @" using System; class Program { static void M() { DayOfWeek x[||] = 0; object y = x; Console.WriteLine(y); } }", @" using System; class Program { static void M() { object y = (DayOfWeek)0; Console.WriteLine(y); } }", parseOptions: null); } [WorkItem(544636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544636")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded1() { await TestAsync( @" using System; class Program { static void M() { Action a[||] = Console.WriteLine; Action b = a + Console.WriteLine; } }", @" using System; class Program { static void M() { Action b = (Action)Console.WriteLine + Console.WriteLine; } }", parseOptions: null); } [WorkItem(544978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544978")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded2() { await TestAsync( @" using System; class Program { static void Main() { Action a[||] = Console.WriteLine; object b = a; } }", @" using System; class Program { static void Main() { object b = (Action)Console.WriteLine; } }", parseOptions: null); } [WorkItem(545103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForTypeThatNoLongerBindsToTheSameType() { await TestAsync( @" class A<T> { static T x; class B<U> { static void Goo() { var y[||] = x; var z = y; } } }", @" class A<T> { static T x; class B<U> { static void Goo() { var z = x; } } }", parseOptions: null); } [WorkItem(545170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545170")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCorrectCastForDelegateCreationExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Predicate<object> x[||] = y => true; var z = new Func<string, bool>(x); } } ", @" using System; class Program { static void Main() { var z = new Func<string, bool>(y => true); } } "); } [WorkItem(545523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545523")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForObjectCreationIfUnneeded() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Exception e[||] = new ArgumentException(); Type b = e.GetType(); } } ", @" using System; class Program { static void Main() { Type b = new ArgumentException().GetType(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastInForeachIfUnneeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections.Generic; class Program { static void Main() { IEnumerable<char> s[||] = ""abc""; foreach (var x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections.Generic; class Program { static void Main() { foreach (var x in ""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (object x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (object x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded02() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (char x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (char x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToKeepGenericMethodInference() { await TestInRegularAndScriptAsync( @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { long [||]x = 1; IComparable<long> c = Goo(x, x); } } ", @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { IComparable<long> c = Goo(1, (long)1); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForKeepImplicitArrayInference() { await TestInRegularAndScriptAsync( @" class C { static void M() { object x[||] = null; var a = new[] { x, x }; Goo(a); } static void Goo(object[] o) { } } ", @" class C { static void M() { var a = new[] { null, (object)null }; Goo(a); } static void Goo(object[] o) { } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolution() { await TestInRegularAndScriptAsync( @" class C { static void M() { long x[||] = 42; Goo(x, x); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }", @" class C { static void M() { Goo(42, (long)42); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolutionInLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void M() { long x[||] = 42; Goo(() => { return x; }, () => { return x; }); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }", @" using System; class C { static void M() { Goo(() => { return 42; }, (Func<long>)(() => { return 42; })); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakResolutionOfOperatorOverloads() { await TestInRegularAndScriptAsync( @" using System; class C { private int value; void M() { C x[||] = 42; Console.WriteLine(x + x); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }", @" using System; class C { private int value; void M() { Console.WriteLine(42 + (C)42); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }"); } [WorkItem(545561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545561")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUncheckedContext() { await TestInRegularAndScriptAsync( @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { var a[||] = Goo(X => (byte)X.Value, null); unchecked { Console.WriteLine(a); } } }", @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { unchecked { Console.WriteLine(Goo(X => (byte)X.Value, (object)null)); } } }"); } [WorkItem(545564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545564")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUnsafeContext() { await TestInRegularAndScriptAsync( @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { var a[||] = Outer(x => Inner(x, null), null); unsafe { Console.WriteLine(a); } } }", @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { unsafe { Console.WriteLine(Outer(x => Inner(x, null), (object)null)); } } }"); } [WorkItem(545783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545783")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInNestedLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo(x => { string s[||] = x; var y = s; }); } }", @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo((Action<string>)(x => { var y = x; })); } }"); } [WorkItem(546069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546069")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestBrokenVariableDeclarator() { await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int [||]a[10] = { 0, 0 }; System.Console.WriteLine(a); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion1() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion2() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion3() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(); #line default } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion4() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(); #line default Goo(x); } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default Goo(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion5() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(x); #line default Goo(x); } }"); } [WorkItem(530743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFromLabeledStatement() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { label: int [||]x = 1; Console.WriteLine(); int y = x; } }", @" using System; class Program { static void Main() { label: Console.WriteLine(); int y = 1; } }"); } [WorkItem(529698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineCompoundAssignmentIntoInitializer() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { int x = 0; int y[||] = x += 1; var z = new List<int> { y }; } }", @" using System.Collections.Generic; class Program { static void Main() { int x = 0; var z = new List<int> { (x += 1) }; } }"); } [WorkItem(609497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609497() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> x[||] = new List<object>(); IList<object> y = x; } }", @" using System.Collections.Generic; class Program { static void Main() { IList<object> y = new List<object>(); } }"); } [WorkItem(636319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_636319() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<object> x[||] = new List<dynamic>(); IList<dynamic> y = x; } } ", @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> y = new List<dynamic>(); } } "); } [WorkItem(609492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609492")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609492() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { ValueType x[||] = 1; object y = x; } } ", @" using System; class Program { static void Main() { object y = 1; } } "); } [WorkItem(529950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529950")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempDoesNotInsertUnnecessaryExplicitTypeInLambdaParameter() { await TestInRegularAndScriptAsync( @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { var z[||] = x; Action a = () => z.GetType(); }, y), null); } } ", @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { Action a = () => x.GetType(); }, y), null); } } "); } [WorkItem(619425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619425")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_619425_RestrictedSimpleNameExpansion() { await TestInRegularAndScriptAsync( @" class A<B> { class C : A<C> { class B : C { void M() { var x[||] = new C[0]; C[] y = x; } } } } ", @" class A<B> { class C : A<C> { class B : C { void M() { C[] y = new C[0]; } } } } "); } [WorkItem(529840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_529840_DetectSemanticChangesAtInlineSite() { await TestInRegularAndScriptAsync( @" using System; class A { static void Main() { var a[||] = new A(); // Inline a Goo(a); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } ", @" using System; class A { static void Main() { // Inline a Goo(new A()); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } "); } [WorkItem(1091946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091946")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConversion() { await TestInRegularAndScriptAsync( @"class A { bool M(string[] args) { var [|x|] = args[0]; return x?.Length == 0; } }", @"class A { bool M(string[] args) { return args[0]?.Length == 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSimpleConditionalAccess() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args.Length.ToString(); var y = x?.ToString(); } }", @"class A { void M(string[] args) { var y = args.Length.ToString()?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConditionalExpression() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args[0]?.Length ?? 10; var y = x == 10 ? 10 : 4; } }", @"class A { void M(string[] args) { var y = (args[0]?.Length ?? 10) == 10 ? 10 : 4; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = t?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = (t?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation_2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = (t?.Something2())()?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = ((t?.Something2())()?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAliasQualifiedNameIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { void M() { var [|g|] = global::System.Guid.Empty; var s = $""{g}""; } }", @"class A { void M() { var s = $""{(global::System.Guid.Empty)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolationWithFormatClause() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x:x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23):x}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestInvocationExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { public static void M(string s) { var [|x|] = s.ToUpper(); var y = $""{x}""; } }", @"class A { public static void M(string s) { var y = $""{s.ToUpper()}""; } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithNoInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace($""hello"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task CastInterpolatedStringWhenInliningIntoInvalidCall() { // Note: This is an error case. This test just demonstrates our current behavior. It // is ok if this behavior changes in the future in response to an implementation change. await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace((string)$""hello"", ""world""); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotCastInterpolatedStringWhenInliningIntoValidCall() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = Replace(s1, ""world""); } void Replace(string s1, string s2) { } }", @"class C { public void M() { var s2 = Replace($""hello"", ""world""); } void Replace(string s1, string s2) { } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33108"), Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }"); } [WorkItem(15530, "https://github.com/dotnet/roslyn/issues/15530")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task PArenthesizeAwaitInlinedIntoReducedExtensionMethod() { await TestInRegularAndScriptAsync( @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { var [|t|] = await Task.FromResult(""""); t.Any(); } }", @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { (await Task.FromResult("""")).Any(); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteRequiringFormattableString() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { M($""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(4624, "https://github.com/dotnet/roslyn/issues/4624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteWithFormattableStringOverload() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { M((FormattableString)$""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(9576, "https://github.com/dotnet/roslyn/issues/9576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoLambdaWithReturnStatementWithNoExpression() { const string initial = @" using System; class C { static void M(Action a) { } static void N() { var [||]x = 42; M(() => { Console.WriteLine(x); return; }); } }"; const string expected = @" using System; class C { static void M(Action a) { } static void N() { M(() => { Console.WriteLine(42); return; }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples_Disabled() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; await TestMissingAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1, ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TuplesWithNames() { var code = @" using System; class C { public void M() { (int a, string b) [||]x = (a: 1, b: ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (a: 1, b: ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11028, "https://github.com/dotnet/roslyn/issues/11028")] public async Task TuplesWithDifferentNames() { var code = @" class C { public void M() { (int a, string b) [||]x = (c: 1, d: ""hello""); x.a.ToString(); } }"; var expected = @" class C { public void M() { (((int a, string b))(c: 1, d: ""hello"")).a.ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Deconstruction() { var code = @" using System; class C { public void M() { var [||]temp = new C(); var (x1, x2) = temp; var x3 = temp; } }"; var expected = @" using System; class C { public void M() { {|Warning:var (x1, x2) = new C()|}; var x3 = new C(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(12802, "https://github.com/dotnet/roslyn/issues/12802")] public async Task Deconstruction2() { var code = @" class Program { static void Main() { var [||]kvp = KVP.Create(42, ""hello""); var(x1, x2) = kvp; } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; var expected = @" class Program { static void Main() { var (x1, x2) = KVP.Create(42, ""hello""); } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11958, "https://github.com/dotnet/roslyn/issues/11958")] public async Task EnsureParenthesesInStringConcatenation() { var code = @" class C { void M() { int [||]i = 1 + 2; string s = ""a"" + i; } }"; var expected = @" class C { void M() { string s = ""a"" + (1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, 3); } }"; var expected = @" class C { void M() { var t = (i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, 3); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, /*comment*/ 3 ); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, /*comment*/ 3 ); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoDuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, i); } }"; var expected = @" class C { void M() { var t = (1 + 2, 1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, (i, _)) = (1, (i, 3))); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, ({|Conflict:(int)C.y|}, _)) = (1, (C.y, 3))); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration2() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, _) = (1, 2)); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, _) = (1, 2)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames() { var code = @" class C { void M() { int [||]Rest = 1 + 2; var t = (Rest, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames2() { var code = @" class C { void M() { int [||]Item1 = 1 + 2; var t = (Item1, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_EscapeKeywords() { var code = @" class C { void M() { int [||]@int = 1 + 2; var t = (@int, 3); } }"; var expected = @" class C { void M() { var t = (@int: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_DoNotEscapeContextualKeywords() { var code = @" class C { void M() { int [||]@where = 1 + 2; var t = (@where, 3); } }"; var expected = @" class C { void M() { var t = (where: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_DuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { i, i }; // error already } }"; var expected = @" class C { void M() { var t = new { i = 1 + 2, i = 1 + 2 }; // error already } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_AssignmentEpression() { var code = @" class C { void M() { int j = 0; int [||]i = j = 1; var t = new { i, k = 3 }; } }"; var expected = @" class C { void M() { int j = 0; var t = new { i = j = 1, k = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, /*comment*/ j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, /*comment*/ j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(19247, "https://github.com/dotnet/roslyn/issues/19247")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_LocalFunction() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { var [|testStr|] = ""test""; expand(testStr); void expand(string str) { } } }", @" using System; class C { void M() { expand(""test""); void expand(string str) { } } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_RefParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(ref T x) { var [||]b = M(ref x); return b || b; } }", @" class C { bool M<T>(ref T x) { return {|Warning:M(ref x) || M(ref x)|}; } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_OutParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(out T x) { var [||]b = M(out x); return b || b; } }", @" class C { bool M<T>(out T x) { return {|Warning:M(out x) || M(out x)|}; } }"); } [WorkItem(24791, "https://github.com/dotnet/roslyn/issues/24791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddUnnecessaryCast() { await TestInRegularAndScriptAsync( @"class C { bool M() { var [||]o = M(); if (!o) throw null; throw null; } }", @"class C { bool M() { if (!M()) throw null; throw null; } }"); } [WorkItem(16819, "https://github.com/dotnet/roslyn/issues/16819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddsDuplicateCast() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]o = (Exception)null; Console.Write(o == new Exception()); } }", @"using System; class C { void M() { Console.Write((Exception)null == new Exception()); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, int>; class C { void M() { var [|x|] = (X)(0, 0); var x2 = x; } }", @"using X = System.ValueTuple<int, int>; class C { void M() { var x2 = (X)(0, 0); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfMixedValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var [|x|] = (X)(0, (0, 0)); var x2 = x; } }", @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var x2 = (X)(0, (0, 0)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(35645, "https://github.com/dotnet/roslyn/issues/35645")] public async Task UsingDeclaration() { var code = @" using System; class C : IDisposable { public void M() { using var [||]c = new C(); c.ToString(); } public void Dispose() { } }"; await TestMissingInRegularAndScriptAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections1() { await TestFixOneAsync( @"{ [|int x = 0;|] Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections2() { await TestFixOneAsync( @"{ int [|x = 0|], y = 1; Console.WriteLine(x); }", @"{ int y = 1; Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections3() { await TestFixOneAsync( @"{ int x = 0, [|y = 1|], z = 2; Console.WriteLine(y); }", @"{ int x = 0, z = 2; Console.WriteLine(1); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional1() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional2() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x == true); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true == true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoMultipleConditionalLocations() { await TestInRegularAndScriptAsync( @"class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); System.Diagnostics.Debug.Assert(x); } }", @"class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; {|Warning:System.Diagnostics.Debug.Assert(true)|}; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task OnlyWarnOnConditionalLocations() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); Console.Writeline(x); } }", @"using System; class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; Console.Writeline(true); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(40201, "https://github.com/dotnet/roslyn/issues/40201")] public async Task TestUnaryNegationOfDeclarationPattern() { await TestInRegularAndScriptAsync( @"using System.Threading; class C { void Test() { var [|ct|] = CancellationToken.None; if (!(Helper(ct) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }", @"using System.Threading; class C { void Test() { if (!(Helper(CancellationToken.None) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(18322, "https://github.com/dotnet/roslyn/issues/18322")] public async Task TestInlineIntoExtensionMethodInvokedOnThis() { await TestInRegularAndScriptAsync( @"public class Class1 { void M() { var [|c|] = 8; this.DoStuff(c); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }", @"public class Class1 { void M() { this.DoStuff(8); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }"); } [WorkItem(8716, "https://github.com/dotnet/roslyn/issues/8716")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyInlinedLocalFunction() { await TestInRegularAndScriptAsync(@" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } var [||]local = new Action(LocalFunc); local(); } }", @" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } new Action(LocalFunc)(); } }"); } [WorkItem(22540, "https://github.com/dotnet/roslyn/issues/22540")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyWhenInliningIntoPattern_01() { await TestInRegularAndScriptAsync(@" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { ExpressionSyntax [||]expression = awaitExpression.Expression; if (!(expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }", @" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { if (!(awaitExpression.Expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }"); } [WorkItem(45661, "https://github.com/dotnet/roslyn/issues/45661")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyWhenInliningIntoPattern_02() { await TestInRegularAndScriptAsync(@" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { ExpressionSyntax [||]expression = awaitExpression.Expression; if (!(expression is ParenthesizedExpressionSyntax { } parenthesizedExpression)) return; } }", @" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { if (!(awaitExpression.Expression is ParenthesizedExpressionSyntax { } parenthesizedExpression)) return; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().P = 1|}; var c2 = new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_IgnoreParentheses() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = (new C()); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C()).P = 1|}; var c2 = (new C()); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = M2(); c.P = 1; var c2 = c; } C M2() { return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:M2().P = 1|}; var c2 = M2(); } C M2() { return new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation2() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.M2(); var c2 = c; } void M2() { P = 1; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().M2()|}; var c2 = new C(); } void M2() { P = 1; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedObjectInitialization() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { new C() }; c[0].P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { new C() })[0].P = 1|}; var c2 = new C[1] { new C() }; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedMethodCall() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { M2() }; c[0].P = 1; var c2 = c; } C M2() { P += 1; return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { M2() })[0].P = 1|}; var c2 = new C[1] { M2() }; } C M2() { P += 1; return new C(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoWithExpression() { await TestInRegularAndScriptAsync(@" record Person(string Name) { void M(Person p) { string [||]x = """"; _ = p with { Name = x }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", @" record Person(string Name) { void M(Person p) { _ = p with { Name = """" }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] public async Task Call_TopLevelStatement() { var code = @" using System; int [||]x = 1 + 1; x.ToString(); "; var expected = @" using System; (1 + 1).ToString(); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 var code = @" int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); "; var expected = @" int val = 0; global::System.Console.WriteLine(val + 1); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement_InScope() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 await TestAsync(@" { int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); } ", @" { int val = 0; global::System.Console.WriteLine(val + 1); } ", TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestWithLinkedFile() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.1'> <Document FilePath='C.cs'> using System.Collections.Generic; namespace Whatever { public class Goo { public void Bar() { var target = new List&lt;object;gt>(); var [||]newItems = new List&lt;Goo&gt;(); target.AddRange(newItems); } } } </Document> </Project> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.2'> <Document IsLinkFile='true' LinkProjectName='CSProj.1' LinkFilePath='C.cs'/> </Project> </Workspace>", @"<Workspace> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.1'> <Document FilePath='C.cs'> using System.Collections.Generic; namespace Whatever { public class Goo { public void Bar() { var target = new List&lt;object;gt>(); target.AddRange(new List&lt;Goo&gt;()); } } } </Document> </Project> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.2'> <Document IsLinkFile='true' LinkProjectName='CSProj.1' LinkFilePath='C.cs'/> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(50207, "https://github.com/dotnet/roslyn/issues/50207")] public async Task TestImplicitObjectCreation() { var code = @" class MyClass { void Test() { MyClass [||]myClass = new(); myClass.ToString(); } } "; var expected = @" class MyClass { void Test() { new MyClass().ToString(); } } "; await TestInRegularAndScriptAsync(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.InlineTemporary { public class InlineTemporaryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new InlineTemporaryCodeRefactoringProvider(); private async Task TestFixOneAsync(string initial, string expected) => await TestInRegularAndScript1Async(GetTreeText(initial), GetTreeText(expected)); private static string GetTreeText(string initial) { return @"class C { void F() " + initial + @" }"; } private static SyntaxNode GetNodeToFix(dynamic initialRoot, int declaratorIndex) => initialRoot.Members[0].Members[0].Body.Statements[0].Declaration.Variables[declaratorIndex]; private static SyntaxNode GetFixedNode(dynamic fixedRoot) => fixedRoot.Members[0].Members[0].BodyOpt; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer1() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer2() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = ; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnSecondWithNoInitializer() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 42, [||]y; System.Console.WriteLine(y); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnField() { await TestMissingInRegularAndScriptAsync( @"class C { int [||]x = 42; void M() { System.Console.WriteLine(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WithRefInitializer1() { await TestMissingInRegularAndScriptAsync( @"class C { ref int M() { int[] arr = new[] { 1, 2, 3 }; ref int [||]x = ref arr[2]; return ref x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task SingleStatement() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 27; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_First() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 0, y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Second() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, [||]y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Last() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, y = 1, [||]z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping1() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping2() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping3() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping4() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping5() { var code = @" using System.Linq; class C { static void Main() { var @where[||] = 0; var q = from e in """" let a = new { @where } select a; } }"; var expected = @" using System.Linq; class C { static void Main() { var q = from e in """" let a = new { @where = 0 } select a; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Call() { var code = @" using System; class C { public void M() { int [||]x = 1 + 1; x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1 + 1).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoChange() { var code = @" using System; class C { public void M() { double [||]x = 3; x.ToString(); } }"; var expected = @" using System; class C { public void M() { ((double)3).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoConversion() { await TestFixOneAsync( @"{ int [||]x = 3; x.ToString(); }", @"{ 3.ToString(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentOverload() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { double [||]x = 3; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((double)3); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(""hi""); } } ", @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { ((Base)new Derived()).M(""hi""); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_SameMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(3); } } ", @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { new Derived().M(3); } } "); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] public async Task Conversion_NonTargetTypedConditionalExpression(LanguageVersion languageVersion) { await TestInRegularAndScriptAsync( @" class C { void F() { int? [||]x = 42; var y = true ? x : null; } } ", @" class C { void F() { var y = true ? (int?)42 : null; } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [InlineData(LanguageVersion.CSharp8, "(int?)42")] [InlineData(LanguageVersion.CSharp9, "42")] // In C# 9, target-typed conditionals makes this work public async Task Conversion_TargetTypedConditionalExpression(LanguageVersion languageVersion, string expectedSubstitution) { await TestInRegularAndScriptAsync( @" class C { void F() { int? [||]x = 42; int? y = true ? x : null; } } ", @" class C { void F() { int? y = true ? " + expectedSubstitution + @" : null; } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NoCastOnVar() { await TestFixOneAsync( @"{ var [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoubleAssignment() { var code = @" class C { void M() { int [||]x = x = 1; int y = x; } }"; var expected = @" class C { void M() { int y = 1; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAnonymousType1() { await TestFixOneAsync( @"{ int [||]x = 42; var a = new { x }; }", @"{ var a = new { x = 42 }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestParenthesizedAtReference_Case3() { await TestFixOneAsync( @"{ int [||]x = 1 + 1; int y = x * 2; }", @"{ int y = (1 + 1) * 2; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontBreakOverloadResolution_Case5() { var code = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { object [||]x = 1 + 1; Goo(x); } }"; var expected = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { Goo((object)(1 + 1)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontTouchUnrelatedBlocks() { var code = @" class C { void M() { int [||]x = 1; { Unrelated(); } Goo(x); } }"; var expected = @" class C { void M() { { Unrelated(); } Goo(1); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLambdaParenthesizeAndCast_Case7() { var code = @" class C { void M() { System.Func<int> [||]x = () => 1; int y = x(); } }"; var expected = @" class C { void M() { int y = ((System.Func<int>)(() => 1))(); } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity1() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094"), WorkItem(541462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity2() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; object [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity3() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (int)1; F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (int)1)); } int f = 0; }"); } [WorkItem(544924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544924")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity4() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1+2); Bar(x < x, x > y); } static void Bar(object a, object b) { } }", @" class Program { static void Main() { int x = 2; Bar(x < x, (x > (1 + 2))); } static void Bar(object a, object b) { } }"); } [WorkItem(544613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544613")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity5() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1 + 2); var z = new[] { x < x, x > y }; } }", @" class Program { static void Main() { int x = 2; var z = new[] { x < x, (x > (1 + 2)) }; } }"); } [WorkItem(538131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538131")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer() { await TestFixOneAsync( @"{ int[] [||]x = { 3, 4, 5 }; int a = Array.IndexOf(x, 3); }", @"{ int a = Array.IndexOf(new int[] { 3, 4, 5 }, 3); }"); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer2() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer3() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter1() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(ref x); Goo(x); } void Goo(int x) { } void Goo(ref int x) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(ref {|Conflict:x|}); Goo(0); } void Goo(int x) { } void Goo(ref int x) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter2() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(x, ref x); } void Goo(int x, ref int y) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(0, ref {|Conflict:x|}); } void Goo(int x, ref int y) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i = 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} = 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression1() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i += 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} += 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression2() { var initial = @"using System; class C { static int x; static void M() { int [||]x = (x = 0) + (x += 1); int y = x; } }"; var expected = @"using System; class C { static int x; static void M() { int x = ({|Conflict:x|} = 0) + ({|Conflict:x|} += 1); int y = 0 + ({|Conflict:x|} += 1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_SubtractAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i -= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} -= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_MultiplyAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i *= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} *= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_DivideAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i /= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} /= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ModuloAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i %= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} %= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AndAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i &= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} &= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_OrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i |= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} |= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ExclusiveOrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i ^= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} ^= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_LeftShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i <<= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} <<= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RightShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i >>= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} >>= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i++; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}++; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; ++i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; ++{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i--; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}--; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; --i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; --{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddressOfExpression() { var initial = @" class C { unsafe void M() { int x = 0; var y[||] = &x; var z = &y; } }"; var expected = @" class C { unsafe void M() { int x = 0; var y = &x; var z = &{|Conflict:y|}; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545342")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_UsedBeforeDeclaration() { var initial = @"class Program { static void Main(string[] args) { var x = y; var y[||] = 45; } }"; var expected = @"class Program { static void Main(string[] args) { var x = {|Conflict:y|}; var y = 45; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor1() { await TestFixOneAsync(@" { int [||]x = 1, #if true y, #endif z; int a = x; }", @" { int #if true y, #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor2() { await TestFixOneAsync(@" { int y, #if true [||]x = 1, #endif z; int a = x; }", @" { int y, #if true #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor3() { await TestFixOneAsync(@" { int y, #if true z, #endif [||]x = 1; int a = x; }", @" { int y, #if true z #endif ; int a = 1; }"); } [WorkItem(540164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540164")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TriviaOnArrayInitializer() { var initial = @"class C { void M() { int[] [||]a = /**/{ 1 }; Goo(a); } }"; var expected = @"class C { void M() { Goo(new int[]/**/{ 1 }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator1() { var initial = @"class C { void M() { int [||]i = 1, j = 2, k = 3; System.Console.Write(i); } }"; var expected = @"class C { void M() { int j = 2, k = 3; System.Console.Write(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator2() { var initial = @"class C { void M() { int i = 1, [||]j = 2, k = 3; System.Console.Write(j); } }"; var expected = @"class C { void M() { int i = 1, k = 3; System.Console.Write(2); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator3() { var initial = @"class C { void M() { int i = 1, j = 2, [||]k = 3; System.Console.Write(k); } }"; var expected = @"class C { void M() { int i = 1, j = 2; System.Console.Write(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540186")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatAnonymousTypeMember() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(6356, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineToAnonymousTypeProperty() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x = x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(528075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528075")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoDelegateInvocation() { var initial = @"using System; class Program { static void Main(string[] args) { Action<string[]> [||]del = Main; del(null); } }"; var expected = @"using System; class Program { static void Main(string[] args) { ((Action<string[]>)Main)(null); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineAnonymousMethodIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = delegate { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)delegate { } ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineLambdaIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = () => { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)(() => { }) ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation1() { var initial = @"using System; class A { static void Main() { long x[||] = 1; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { object z = (long)1; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation2() { var initial = @"using System; class A { static void Main() { int y = 1; long x[||] = y; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { int y = 1; object z = (long)y; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation3() { var initial = @"using System; class A { static void Main() { byte x[||] = 1; object z = x; Console.WriteLine((byte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (byte)1; Console.WriteLine((byte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation4() { var initial = @"using System; class A { static void Main() { sbyte x[||] = 1; object z = x; Console.WriteLine((sbyte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (sbyte)1; Console.WriteLine((sbyte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation5() { var initial = @"using System; class A { static void Main() { short x[||] = 1; object z = x; Console.WriteLine((short)z); } }"; var expected = @"using System; class A { static void Main() { object z = (short)1; Console.WriteLine((short)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestPreprocessor() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { #if true int [||]i = 10; //print Console.Write(i); #endif } }", @"class Program { static void Main(string[] args) { #if true //print Console.Write(10); #endif } }"); } [WorkItem(540277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540277")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestFormatting() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 5; int j = 110; Console.Write(i + j); } }", @"class Program { static void Main(string[] args) { int j = 110; Console.Write(5 + j); } }"); } [WorkItem(541694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541694")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSwitchSection() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { switch (10) { default: int i[||] = 10; Console.WriteLine(i); break; } } }", @"using System; class C { void M() { switch (10) { default: Console.WriteLine(10); break; } } }"); } [WorkItem(542647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded1() { await TestInRegularAndScriptAsync( @" using System; class C { static Action X; static void M() { var [||]y = (X); y(); } } ", @" using System; class C { static Action X; static void M() { X(); } } "); } [WorkItem(545619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545619")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Action x = Console.WriteLine; Action y[||] = x; y(); } } ", @" using System; class Program { static void Main() { Action x = Console.WriteLine; x(); } } "); } [WorkItem(542656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542656")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary1() { await TestInRegularAndScriptAsync( @"using System; using System.Collections; using System.Linq; class A { static void Main() { var [||]q = from x in """" select x; if (q is IEnumerable) { } } }", @"using System; using System.Collections; using System.Linq; class A { static void Main() { if ((from x in """" select x) is IEnumerable) { } } }"); } [WorkItem(544626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544626")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Action<string> f[||] = Goo<string>; Action<string> g = null; var h = f + g; } static void Goo<T>(T y) { } }", @" using System; class C { static void Main() { Action<string> g = null; var h = Goo + g; } static void Goo<T>(T y) { } }"); } [WorkItem(544415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544415")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = (Int32)p; } }", @" using System; unsafe class C { static void M() { int x; var i = (Int32)(&x); } }"); } [WorkItem(544922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544922")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = p->ToString(); } }", @" using System; unsafe class C { static void M() { int x; var i = (&x)->ToString(); } }"); } [WorkItem(544921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544921")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int* x = null; int p[||] = *x; var i = (Int64)p; } }", @" using System; unsafe class C { static void M() { int* x = null; var i = (Int64)(*x); } }"); } [WorkItem(544614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544614")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int** x = null; int* p[||] = *x; var i = p[1].ToString(); } }", @" using System; unsafe class C { static void M() { int** x = null; var i = (*x)[1].ToString(); } }"); } [WorkItem(544563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544563")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInlineStackAlloc() { await TestMissingInRegularAndScriptAsync( @"using System; unsafe class C { static void M() { int* values[||] = stackalloc int[20]; int* copy = values; int* p = &values[1]; int* q = &values[15]; } }"); } [WorkItem(543744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempLambdaExpressionCastingError() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int?,int?> [||]lam = (int? s) => { return s; }; Console.WriteLine(lam); } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine((int? s) => { return s; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForNull() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { string [||]x = null; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((string)null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded1() { await TestInRegularAndScriptAsync( @" class C { void M() { long x[||] = 1; System.IComparable<long> y = x; } }", @" class C { void M() { System.IComparable<long> y = (long)1; } }"); } [WorkItem(545161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545161")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Goo(x => { int [||]y = x[0]; x[1] = y; }); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }", @" using System; class C { static void Main() { Goo((Action<int[]>)(x => { x[1] = x[0]; })); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }"); } [WorkItem(544612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544612")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoBracketedList() { await TestInRegularAndScriptAsync( @" class C { void M() { var c = new C(); int x[||] = 1; c[x] = 2; } int this[object x] { set { } } }", @" class C { void M() { var c = new C(); c[1] = 2; } int this[object x] { set { } } }"); } [WorkItem(542648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542648")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAfterCastIfNeeded() { await TestAsync( @" using System; enum E { } class Program { static void Main() { E x[||] = (global::E) -1; object y = x; } }", @" using System; enum E { } class Program { static void Main() { object y = (global::E)-1; } }", parseOptions: null); } [WorkItem(544635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544635")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForEnumZeroIfBoxed() { await TestAsync( @" using System; class Program { static void M() { DayOfWeek x[||] = 0; object y = x; Console.WriteLine(y); } }", @" using System; class Program { static void M() { object y = (DayOfWeek)0; Console.WriteLine(y); } }", parseOptions: null); } [WorkItem(544636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544636")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded1() { await TestAsync( @" using System; class Program { static void M() { Action a[||] = Console.WriteLine; Action b = a + Console.WriteLine; } }", @" using System; class Program { static void M() { Action b = (Action)Console.WriteLine + Console.WriteLine; } }", parseOptions: null); } [WorkItem(544978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544978")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded2() { await TestAsync( @" using System; class Program { static void Main() { Action a[||] = Console.WriteLine; object b = a; } }", @" using System; class Program { static void Main() { object b = (Action)Console.WriteLine; } }", parseOptions: null); } [WorkItem(545103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForTypeThatNoLongerBindsToTheSameType() { await TestAsync( @" class A<T> { static T x; class B<U> { static void Goo() { var y[||] = x; var z = y; } } }", @" class A<T> { static T x; class B<U> { static void Goo() { var z = x; } } }", parseOptions: null); } [WorkItem(545170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545170")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCorrectCastForDelegateCreationExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Predicate<object> x[||] = y => true; var z = new Func<string, bool>(x); } } ", @" using System; class Program { static void Main() { var z = new Func<string, bool>(y => true); } } "); } [WorkItem(545523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545523")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForObjectCreationIfUnneeded() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Exception e[||] = new ArgumentException(); Type b = e.GetType(); } } ", @" using System; class Program { static void Main() { Type b = new ArgumentException().GetType(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastInForeachIfUnneeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections.Generic; class Program { static void Main() { IEnumerable<char> s[||] = ""abc""; foreach (var x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections.Generic; class Program { static void Main() { foreach (var x in ""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (object x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (object x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded02() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (char x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (char x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToKeepGenericMethodInference() { await TestInRegularAndScriptAsync( @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { long [||]x = 1; IComparable<long> c = Goo(x, x); } } ", @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { IComparable<long> c = Goo(1, (long)1); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForKeepImplicitArrayInference() { await TestInRegularAndScriptAsync( @" class C { static void M() { object x[||] = null; var a = new[] { x, x }; Goo(a); } static void Goo(object[] o) { } } ", @" class C { static void M() { var a = new[] { null, (object)null }; Goo(a); } static void Goo(object[] o) { } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolution() { await TestInRegularAndScriptAsync( @" class C { static void M() { long x[||] = 42; Goo(x, x); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }", @" class C { static void M() { Goo(42, (long)42); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolutionInLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void M() { long x[||] = 42; Goo(() => { return x; }, () => { return x; }); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }", @" using System; class C { static void M() { Goo(() => { return 42; }, (Func<long>)(() => { return 42; })); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakResolutionOfOperatorOverloads() { await TestInRegularAndScriptAsync( @" using System; class C { private int value; void M() { C x[||] = 42; Console.WriteLine(x + x); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }", @" using System; class C { private int value; void M() { Console.WriteLine(42 + (C)42); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }"); } [WorkItem(545561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545561")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUncheckedContext() { await TestInRegularAndScriptAsync( @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { var a[||] = Goo(X => (byte)X.Value, null); unchecked { Console.WriteLine(a); } } }", @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { unchecked { Console.WriteLine(Goo(X => (byte)X.Value, (object)null)); } } }"); } [WorkItem(545564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545564")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUnsafeContext() { await TestInRegularAndScriptAsync( @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { var a[||] = Outer(x => Inner(x, null), null); unsafe { Console.WriteLine(a); } } }", @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { unsafe { Console.WriteLine(Outer(x => Inner(x, null), (object)null)); } } }"); } [WorkItem(545783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545783")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInNestedLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo(x => { string s[||] = x; var y = s; }); } }", @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo((Action<string>)(x => { var y = x; })); } }"); } [WorkItem(546069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546069")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestBrokenVariableDeclarator() { await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int [||]a[10] = { 0, 0 }; System.Console.WriteLine(a); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion1() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion2() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion3() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(); #line default } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion4() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(); #line default Goo(x); } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default Goo(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion5() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(x); #line default Goo(x); } }"); } [WorkItem(530743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFromLabeledStatement() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { label: int [||]x = 1; Console.WriteLine(); int y = x; } }", @" using System; class Program { static void Main() { label: Console.WriteLine(); int y = 1; } }"); } [WorkItem(529698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineCompoundAssignmentIntoInitializer() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { int x = 0; int y[||] = x += 1; var z = new List<int> { y }; } }", @" using System.Collections.Generic; class Program { static void Main() { int x = 0; var z = new List<int> { (x += 1) }; } }"); } [WorkItem(609497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609497() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> x[||] = new List<object>(); IList<object> y = x; } }", @" using System.Collections.Generic; class Program { static void Main() { IList<object> y = new List<object>(); } }"); } [WorkItem(636319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_636319() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<object> x[||] = new List<dynamic>(); IList<dynamic> y = x; } } ", @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> y = new List<dynamic>(); } } "); } [WorkItem(609492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609492")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609492() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { ValueType x[||] = 1; object y = x; } } ", @" using System; class Program { static void Main() { object y = 1; } } "); } [WorkItem(529950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529950")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempDoesNotInsertUnnecessaryExplicitTypeInLambdaParameter() { await TestInRegularAndScriptAsync( @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { var z[||] = x; Action a = () => z.GetType(); }, y), null); } } ", @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { Action a = () => x.GetType(); }, y), null); } } "); } [WorkItem(619425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619425")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_619425_RestrictedSimpleNameExpansion() { await TestInRegularAndScriptAsync( @" class A<B> { class C : A<C> { class B : C { void M() { var x[||] = new C[0]; C[] y = x; } } } } ", @" class A<B> { class C : A<C> { class B : C { void M() { C[] y = new C[0]; } } } } "); } [WorkItem(529840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_529840_DetectSemanticChangesAtInlineSite() { await TestInRegularAndScriptAsync( @" using System; class A { static void Main() { var a[||] = new A(); // Inline a Goo(a); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } ", @" using System; class A { static void Main() { // Inline a Goo(new A()); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } "); } [WorkItem(1091946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091946")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConversion() { await TestInRegularAndScriptAsync( @"class A { bool M(string[] args) { var [|x|] = args[0]; return x?.Length == 0; } }", @"class A { bool M(string[] args) { return args[0]?.Length == 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSimpleConditionalAccess() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args.Length.ToString(); var y = x?.ToString(); } }", @"class A { void M(string[] args) { var y = args.Length.ToString()?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConditionalExpression() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args[0]?.Length ?? 10; var y = x == 10 ? 10 : 4; } }", @"class A { void M(string[] args) { var y = (args[0]?.Length ?? 10) == 10 ? 10 : 4; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = t?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = (t?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation_2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = (t?.Something2())()?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = ((t?.Something2())()?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAliasQualifiedNameIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { void M() { var [|g|] = global::System.Guid.Empty; var s = $""{g}""; } }", @"class A { void M() { var s = $""{(global::System.Guid.Empty)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolationWithFormatClause() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x:x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23):x}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestInvocationExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { public static void M(string s) { var [|x|] = s.ToUpper(); var y = $""{x}""; } }", @"class A { public static void M(string s) { var y = $""{s.ToUpper()}""; } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithNoInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace($""hello"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task CastInterpolatedStringWhenInliningIntoInvalidCall() { // Note: This is an error case. This test just demonstrates our current behavior. It // is ok if this behavior changes in the future in response to an implementation change. await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace((string)$""hello"", ""world""); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotCastInterpolatedStringWhenInliningIntoValidCall() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = Replace(s1, ""world""); } void Replace(string s1, string s2) { } }", @"class C { public void M() { var s2 = Replace($""hello"", ""world""); } void Replace(string s1, string s2) { } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33108"), Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }"); } [WorkItem(15530, "https://github.com/dotnet/roslyn/issues/15530")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task PArenthesizeAwaitInlinedIntoReducedExtensionMethod() { await TestInRegularAndScriptAsync( @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { var [|t|] = await Task.FromResult(""""); t.Any(); } }", @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { (await Task.FromResult("""")).Any(); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteRequiringFormattableString() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { M($""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(4624, "https://github.com/dotnet/roslyn/issues/4624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteWithFormattableStringOverload() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { M((FormattableString)$""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(9576, "https://github.com/dotnet/roslyn/issues/9576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoLambdaWithReturnStatementWithNoExpression() { const string initial = @" using System; class C { static void M(Action a) { } static void N() { var [||]x = 42; M(() => { Console.WriteLine(x); return; }); } }"; const string expected = @" using System; class C { static void M(Action a) { } static void N() { M(() => { Console.WriteLine(42); return; }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples_Disabled() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; await TestMissingAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1, ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TuplesWithNames() { var code = @" using System; class C { public void M() { (int a, string b) [||]x = (a: 1, b: ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (a: 1, b: ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11028, "https://github.com/dotnet/roslyn/issues/11028")] public async Task TuplesWithDifferentNames() { var code = @" class C { public void M() { (int a, string b) [||]x = (c: 1, d: ""hello""); x.a.ToString(); } }"; var expected = @" class C { public void M() { (((int a, string b))(c: 1, d: ""hello"")).a.ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Deconstruction() { var code = @" using System; class C { public void M() { var [||]temp = new C(); var (x1, x2) = temp; var x3 = temp; } }"; var expected = @" using System; class C { public void M() { {|Warning:var (x1, x2) = new C()|}; var x3 = new C(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(12802, "https://github.com/dotnet/roslyn/issues/12802")] public async Task Deconstruction2() { var code = @" class Program { static void Main() { var [||]kvp = KVP.Create(42, ""hello""); var(x1, x2) = kvp; } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; var expected = @" class Program { static void Main() { var (x1, x2) = KVP.Create(42, ""hello""); } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11958, "https://github.com/dotnet/roslyn/issues/11958")] public async Task EnsureParenthesesInStringConcatenation() { var code = @" class C { void M() { int [||]i = 1 + 2; string s = ""a"" + i; } }"; var expected = @" class C { void M() { string s = ""a"" + (1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, 3); } }"; var expected = @" class C { void M() { var t = (i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, 3); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, /*comment*/ 3 ); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, /*comment*/ 3 ); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoDuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, i); } }"; var expected = @" class C { void M() { var t = (1 + 2, 1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, (i, _)) = (1, (i, 3))); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, ({|Conflict:(int)C.y|}, _)) = (1, (C.y, 3))); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration2() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, _) = (1, 2)); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, _) = (1, 2)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames() { var code = @" class C { void M() { int [||]Rest = 1 + 2; var t = (Rest, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames2() { var code = @" class C { void M() { int [||]Item1 = 1 + 2; var t = (Item1, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_EscapeKeywords() { var code = @" class C { void M() { int [||]@int = 1 + 2; var t = (@int, 3); } }"; var expected = @" class C { void M() { var t = (@int: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_DoNotEscapeContextualKeywords() { var code = @" class C { void M() { int [||]@where = 1 + 2; var t = (@where, 3); } }"; var expected = @" class C { void M() { var t = (where: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_DuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { i, i }; // error already } }"; var expected = @" class C { void M() { var t = new { i = 1 + 2, i = 1 + 2 }; // error already } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_AssignmentEpression() { var code = @" class C { void M() { int j = 0; int [||]i = j = 1; var t = new { i, k = 3 }; } }"; var expected = @" class C { void M() { int j = 0; var t = new { i = j = 1, k = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, /*comment*/ j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, /*comment*/ j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(19247, "https://github.com/dotnet/roslyn/issues/19247")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_LocalFunction() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { var [|testStr|] = ""test""; expand(testStr); void expand(string str) { } } }", @" using System; class C { void M() { expand(""test""); void expand(string str) { } } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_RefParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(ref T x) { var [||]b = M(ref x); return b || b; } }", @" class C { bool M<T>(ref T x) { return {|Warning:M(ref x) || M(ref x)|}; } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_OutParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(out T x) { var [||]b = M(out x); return b || b; } }", @" class C { bool M<T>(out T x) { return {|Warning:M(out x) || M(out x)|}; } }"); } [WorkItem(24791, "https://github.com/dotnet/roslyn/issues/24791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddUnnecessaryCast() { await TestInRegularAndScriptAsync( @"class C { bool M() { var [||]o = M(); if (!o) throw null; throw null; } }", @"class C { bool M() { if (!M()) throw null; throw null; } }"); } [WorkItem(16819, "https://github.com/dotnet/roslyn/issues/16819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddsDuplicateCast() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]o = (Exception)null; Console.Write(o == new Exception()); } }", @"using System; class C { void M() { Console.Write((Exception)null == new Exception()); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, int>; class C { void M() { var [|x|] = (X)(0, 0); var x2 = x; } }", @"using X = System.ValueTuple<int, int>; class C { void M() { var x2 = (X)(0, 0); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfMixedValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var [|x|] = (X)(0, (0, 0)); var x2 = x; } }", @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var x2 = (X)(0, (0, 0)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(35645, "https://github.com/dotnet/roslyn/issues/35645")] public async Task UsingDeclaration() { var code = @" using System; class C : IDisposable { public void M() { using var [||]c = new C(); c.ToString(); } public void Dispose() { } }"; await TestMissingInRegularAndScriptAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections1() { await TestFixOneAsync( @"{ [|int x = 0;|] Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections2() { await TestFixOneAsync( @"{ int [|x = 0|], y = 1; Console.WriteLine(x); }", @"{ int y = 1; Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections3() { await TestFixOneAsync( @"{ int x = 0, [|y = 1|], z = 2; Console.WriteLine(y); }", @"{ int x = 0, z = 2; Console.WriteLine(1); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional1() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional2() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x == true); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true == true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoMultipleConditionalLocations() { await TestInRegularAndScriptAsync( @"class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); System.Diagnostics.Debug.Assert(x); } }", @"class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; {|Warning:System.Diagnostics.Debug.Assert(true)|}; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task OnlyWarnOnConditionalLocations() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); Console.Writeline(x); } }", @"using System; class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; Console.Writeline(true); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(40201, "https://github.com/dotnet/roslyn/issues/40201")] public async Task TestUnaryNegationOfDeclarationPattern() { await TestInRegularAndScriptAsync( @"using System.Threading; class C { void Test() { var [|ct|] = CancellationToken.None; if (!(Helper(ct) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }", @"using System.Threading; class C { void Test() { if (!(Helper(CancellationToken.None) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(18322, "https://github.com/dotnet/roslyn/issues/18322")] public async Task TestInlineIntoExtensionMethodInvokedOnThis() { await TestInRegularAndScriptAsync( @"public class Class1 { void M() { var [|c|] = 8; this.DoStuff(c); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }", @"public class Class1 { void M() { this.DoStuff(8); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }"); } [WorkItem(8716, "https://github.com/dotnet/roslyn/issues/8716")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyInlinedLocalFunction() { await TestInRegularAndScriptAsync(@" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } var [||]local = new Action(LocalFunc); local(); } }", @" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } new Action(LocalFunc)(); } }"); } [WorkItem(22540, "https://github.com/dotnet/roslyn/issues/22540")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyWhenInliningIntoPattern_01() { await TestInRegularAndScriptAsync(@" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { ExpressionSyntax [||]expression = awaitExpression.Expression; if (!(expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }", @" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { if (!(awaitExpression.Expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }"); } [WorkItem(45661, "https://github.com/dotnet/roslyn/issues/45661")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyWhenInliningIntoPattern_02() { await TestInRegularAndScriptAsync(@" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { ExpressionSyntax [||]expression = awaitExpression.Expression; if (!(expression is ParenthesizedExpressionSyntax { } parenthesizedExpression)) return; } }", @" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { if (!(awaitExpression.Expression is ParenthesizedExpressionSyntax { } parenthesizedExpression)) return; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().P = 1|}; var c2 = new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_IgnoreParentheses() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = (new C()); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C()).P = 1|}; var c2 = (new C()); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = M2(); c.P = 1; var c2 = c; } C M2() { return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:M2().P = 1|}; var c2 = M2(); } C M2() { return new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation2() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.M2(); var c2 = c; } void M2() { P = 1; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().M2()|}; var c2 = new C(); } void M2() { P = 1; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedObjectInitialization() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { new C() }; c[0].P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { new C() })[0].P = 1|}; var c2 = new C[1] { new C() }; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedMethodCall() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { M2() }; c[0].P = 1; var c2 = c; } C M2() { P += 1; return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { M2() })[0].P = 1|}; var c2 = new C[1] { M2() }; } C M2() { P += 1; return new C(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoWithExpression() { await TestInRegularAndScriptAsync(@" record Person(string Name) { void M(Person p) { string [||]x = """"; _ = p with { Name = x }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", @" record Person(string Name) { void M(Person p) { _ = p with { Name = """" }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] public async Task Call_TopLevelStatement() { var code = @" using System; int [||]x = 1 + 1; x.ToString(); "; var expected = @" using System; (1 + 1).ToString(); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 var code = @" int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); "; var expected = @" int val = 0; global::System.Console.WriteLine(val + 1); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement_InScope() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 await TestAsync(@" { int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); } ", @" { int val = 0; global::System.Console.WriteLine(val + 1); } ", TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestWithLinkedFile() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.1'> <Document FilePath='C.cs'> using System.Collections.Generic; namespace Whatever { public class Goo { public void Bar() { var target = new List&lt;object;gt>(); var [||]newItems = new List&lt;Goo&gt;(); target.AddRange(newItems); } } } </Document> </Project> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.2'> <Document IsLinkFile='true' LinkProjectName='CSProj.1' LinkFilePath='C.cs'/> </Project> </Workspace>", @"<Workspace> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.1'> <Document FilePath='C.cs'> using System.Collections.Generic; namespace Whatever { public class Goo { public void Bar() { var target = new List&lt;object;gt>(); target.AddRange(new List&lt;Goo&gt;()); } } } </Document> </Project> <Project Language='C#' CommonReferences='true' AssemblyName='LinkedProj' Name='CSProj.2'> <Document IsLinkFile='true' LinkProjectName='CSProj.1' LinkFilePath='C.cs'/> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(50207, "https://github.com/dotnet/roslyn/issues/50207")] public async Task TestImplicitObjectCreation() { var code = @" class MyClass { void Test() { MyClass [||]myClass = new(); myClass.ToString(); } } "; var expected = @" class MyClass { void Test() { new MyClass().ToString(); } } "; await TestInRegularAndScriptAsync(code, expected, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_InvalidExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ICacheEntry.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { internal interface ICacheEntry<out TKey, out TValue> { TKey Key { get; } TValue Value { 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. namespace Roslyn.Utilities { internal interface ICacheEntry<out TKey, out TValue> { TKey Key { get; } TValue Value { get; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests : CompilingTestBase { private class ComplainAboutX : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_CA9999_UseOfVariableThatStartsWithX = new DiagnosticDescriptor(id: "CA9999_UseOfVariableThatStartsWithX", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_CA9999_UseOfVariableThatStartsWithX); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.IdentifierName); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { var id = (IdentifierNameSyntax)context.Node; if (id.Identifier.ValueText.StartsWith("x", StringComparison.Ordinal)) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_CA9999_UseOfVariableThatStartsWithX, id.Location, id.Identifier.ValueText)); } } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTest() { string source = @"public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics( // (1,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (5,18): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (5,21): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (6,16): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTestInInitializer() { string source = @"delegate int D(out int x); public class C : NotFound { static int x1 = 2; static int x2 = 3; int x3 = x1 + x2; D d1 = (out int x4) => (x4 = 1) + @x4; }"; // TODO: Compilation create doesn't accept analyzers anymore. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,14): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (6,19): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (7,29): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x4").WithArguments("x4"), // (7,39): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "@x4").WithArguments("x4") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerSuppressDiagnostic() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); CreateCompilationWithMscorlib45(source, options: options/*, analyzers: new IDiagnosticAnalyzerFactory[] { new ComplainAboutX() }*/).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsError() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true) ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsErrorGlobal() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true)); } [Fact, WorkItem(1038025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038025")] public void TestImplicitlyDeclaredSymbolsNotAnalyzed() { string source = @" using System; public class C { public event EventHandler e; }"; CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ImplicitlyDeclaredSymbolAnalyzer() }); } private class SyntaxAndSymbolAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor("XX0001", "My Syntax/Symbol Diagnostic", "My Syntax/Symbol Diagnostic for '{0}'", "Compiler", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.Attribute, SyntaxKind.ClassDeclaration, SyntaxKind.UsingDirective); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.Attribute: var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "Attribute"); context.ReportDiagnostic(diag1); break; case SyntaxKind.ClassDeclaration: var diag2 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "ClassDeclaration"); context.ReportDiagnostic(diag2); break; case SyntaxKind.UsingDirective: var diag3 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "UsingDirective"); context.ReportDiagnostic(diag3); break; } } private void AnalyzeSymbol(SymbolAnalysisContext context) { var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Symbol.Locations[0], "NamedType"); context.ReportDiagnostic(diag1); } } [WorkItem(914236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/914236")] [Fact] public void DiagnosticAnalyzerSyntaxNodeAndSymbolAnalysis() { string source = @" using System; [Obsolete] public class C { }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SyntaxAndSymbolAnalyzer() }, null, null, // Symbol diagnostics Diagnostic("XX0001", "C").WithArguments("NamedType").WithWarningAsError(true), // Syntax diagnostics Diagnostic("XX0001", "using System;").WithArguments("UsingDirective").WithWarningAsError(true), // using directive Diagnostic("XX0001", "Obsolete").WithArguments("Attribute").WithWarningAsError(true), // attribute syntax Diagnostic("XX0001", @"[Obsolete] public class C { }").WithArguments("ClassDeclaration").WithWarningAsError(true)); // class declaration } [Fact] public void TestGetEffectiveDiagnostics() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; // Escalate all diagnostics to error. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); foreach (var effectiveDiag in effectiveDiags) { Assert.True(effectiveDiag.Severity == DiagnosticSeverity.Error); } // Suppress all diagnostics. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(0, effectiveDiags.Length); // Shuffle diagnostic severity. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Info); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Hidden); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); var diagIds = new HashSet<string>(diags.Select(d => d.Id)); foreach (var effectiveDiag in effectiveDiags) { Assert.True(diagIds.Remove(effectiveDiag.Id)); switch (effectiveDiag.Severity) { case DiagnosticSeverity.Hidden: Assert.Equal(infoDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Info: Assert.Equal(noneDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Warning: Assert.Equal(errorDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Error: Assert.Equal(warningDiagDescriptor.Id, effectiveDiag.Id); break; default: throw ExceptionUtilities.Unreachable; } } Assert.Empty(diagIds); } [Fact] public void TestGetEffectiveDiagnosticsGlobal() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = Microsoft.CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = Microsoft.CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = Microsoft.CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = Microsoft.CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Default); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.IsWarningAsError)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Warn); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Warning)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Info); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Info)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Hidden); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(2, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); } [Fact] public void TestDisabledDiagnostics() { var disabledDiagDescriptor = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); var enabledDiagDescriptor = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var disabledDiag = CodeAnalysis.Diagnostic.Create(disabledDiagDescriptor, Location.None); var enabledDiag = CodeAnalysis.Diagnostic.Create(enabledDiagDescriptor, Location.None); var diags = new[] { disabledDiag, enabledDiag }; // Verify that only the enabled diag shows up after filtering. var options = TestOptions.ReleaseDll; var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(enabledDiag, effectiveDiags); // If the disabled diag was enabled through options, then it should show up. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(disabledDiagDescriptor.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(enabledDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(disabledDiag, effectiveDiags); } internal class FullyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc3 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2, desc3); } } public override void Initialize(AnalysisContext context) { } } internal class PartiallyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2); } } public override void Initialize(AnalysisContext context) { } } internal class ImplicitlyDeclaredSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("DummyId", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction( (c) => { Assert.False(c.Symbol.IsImplicitlyDeclared); }, SymbolKind.Namespace, SymbolKind.NamedType, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } } [Fact] public void TestDisabledAnalyzers() { var fullyDisabledAnalyzer = new FullyDisabledAnalyzer(); var partiallyDisabledAnalyzer = new PartiallyDisabledAnalyzer(); var options = TestOptions.ReleaseDll; Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.False(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc1.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(PartiallyDisabledAnalyzer.desc2.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.False(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.True(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); // Verify not configurable disabled diagnostic cannot be enabled, and hence cannot affect IsDiagnosticAnalyzerSuppressed computation. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc3.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForNoExecutableCode() { string noExecutableCodeSource = @" public abstract class C { public int P { get; set; } public int field; public abstract int Method(); }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(noExecutableCodeSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForBaseConstructorInitializer() { string baseCtorSource = @" public class B { public B(int x) {} } public class C : B { public C() : base(x: 10) {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(baseCtorSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ConstructorInitializerDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic")); } [Fact, WorkItem(1067286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067286")] public void TestCodeBlockAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestSyntaxNodeAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: false) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestMethodSymbolAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new MethodSymbolAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.Property.get").WithLocation(4, 28), Diagnostic("MethodSymbolDiagnostic", "Method").WithArguments("B.Method()").WithLocation(5, 16), Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.this[int].get").WithLocation(6, 31)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FieldDeclarationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "MyFieldDiagnostic"; internal const string Title = "MyFieldDiagnostic"; internal const string MessageFormat = "MyFieldDiagnostic"; internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; var diagnostic = CodeAnalysis.Diagnostic.Create(Rule, fieldDeclaration.GetLocation()); context.ReportDiagnostic(diagnostic); } } [Fact] public void TestNoDuplicateCallbacksForFieldDeclaration() { string source = @" public class B { public string field = ""field""; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field = ""field"";").WithLocation(4, 5)); } [Fact, WorkItem(565, "https://github.com/dotnet/roslyn/issues/565")] public void TestCallbacksForFieldDeclarationWithMultipleVariables() { string source = @" public class B { public string field1, field2; public int field3 = 0, field4 = 1; public int field5, field6 = 1; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field1, field2;").WithLocation(4, 5), Diagnostic("MyFieldDiagnostic", @"public int field3 = 0, field4 = 1;").WithLocation(5, 5), Diagnostic("MyFieldDiagnostic", @"public int field5, field6 = 1;").WithLocation(6, 5)); } [Fact, WorkItem(1096600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096600")] public void TestDescriptorForConfigurableCompilerDiagnostics() { // Verify that all configurable compiler diagnostics, i.e. all non-error diagnostics, // have a non-null and non-empty Title and Category. // These diagnostic descriptor fields show up in the ruleset editor and hence must have a valid value. var analyzer = new CSharpCompilerDiagnosticAnalyzer(); foreach (var descriptor in analyzer.SupportedDiagnostics) { Assert.True(descriptor.IsEnabledByDefault); if (descriptor.IsNotConfigurable()) { continue; } var title = descriptor.Title.ToString(); if (string.IsNullOrEmpty(title)) { var id = Int32.Parse(descriptor.Id.Substring(2)); var missingResource = Enum.GetName(typeof(ErrorCode), id) + "_Title"; var message = string.Format("Add resource string named '{0}' for Title of '{1}' to '{2}'", missingResource, descriptor.Id, nameof(CSharpResources)); // This assert will fire if you are adding a new compiler diagnostic (non-error severity), // but did not add a title resource string for the diagnostic. Assert.True(false, message); } var category = descriptor.Category; if (string.IsNullOrEmpty(title)) { var message = string.Format("'{0}' must have a non-null non-empty 'Category'", descriptor.Id); Assert.True(false, message); } } } public class CodeBlockOrSyntaxNodeAnalyzer : DiagnosticAnalyzer { private readonly bool _isCodeBlockAnalyzer; public static DiagnosticDescriptor Descriptor1 = DescriptorFactory.CreateSimpleDescriptor("CodeBlockDiagnostic"); public static DiagnosticDescriptor Descriptor2 = DescriptorFactory.CreateSimpleDescriptor("EqualsValueDiagnostic"); public static DiagnosticDescriptor Descriptor3 = DescriptorFactory.CreateSimpleDescriptor("ConstructorInitializerDiagnostic"); public static DiagnosticDescriptor Descriptor4 = DescriptorFactory.CreateSimpleDescriptor("PropertyExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor5 = DescriptorFactory.CreateSimpleDescriptor("IndexerExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor6 = DescriptorFactory.CreateSimpleDescriptor("MethodExpressionBodyDiagnostic"); public CodeBlockOrSyntaxNodeAnalyzer(bool isCodeBlockAnalyzer) { _isCodeBlockAnalyzer = isCodeBlockAnalyzer; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2, Descriptor3, Descriptor4, Descriptor5, Descriptor6); } } public override void Initialize(AnalysisContext context) { if (_isCodeBlockAnalyzer) { context.RegisterCodeBlockStartAction<SyntaxKind>(OnCodeBlockStarted); context.RegisterCodeBlockAction(OnCodeBlockEnded); } else { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } } public static void OnCodeBlockEnded(CodeBlockAnalysisContext context) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, Location.None)); } public static void OnCodeBlockStarted(CodeBlockStartAnalysisContext<SyntaxKind> context) { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } protected class NodeAnalyzer { public void Initialize(Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerSyntaxNodeAction) { registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor2, Location.None)); }, ImmutableArray.Create(SyntaxKind.EqualsValueClause)); registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor3, Location.None)); }, ImmutableArray.Create(SyntaxKind.BaseConstructorInitializer)); registerSyntaxNodeAction(context => { var descriptor = (DiagnosticDescriptor)null; switch (CSharpExtensions.Kind(context.Node.Parent)) { case SyntaxKind.PropertyDeclaration: descriptor = Descriptor4; break; case SyntaxKind.IndexerDeclaration: descriptor = Descriptor5; break; default: descriptor = Descriptor6; break; } context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(descriptor, Location.None)); }, ImmutableArray.Create(SyntaxKind.ArrowExpressionClause)); } } } public class MethodSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor("MethodSymbolDiagnostic", "MethodSymbolDiagnostic", "{0}", "MethodSymbolDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(ctxt => { var method = ((IMethodSymbol)ctxt.Symbol); ctxt.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, method.Locations[0], method.ToDisplayString())); }, SymbolKind.Method); } } [Fact, WorkItem(252, "https://github.com/dotnet/roslyn/issues/252"), WorkItem(1392, "https://github.com/dotnet/roslyn/issues/1392")] public void TestReportingUnsupportedDiagnostic() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzer = new AnalyzerReportingUnsupportedDiagnostic(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; string message = new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedDiagnosticReported, AnalyzerReportingUnsupportedDiagnostic.UnsupportedDescriptor.Id), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID_1")}"; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CSharp.UnitTests.DiagnosticAnalyzerTests+AnalyzerReportingUnsupportedDiagnostic", "System.ArgumentException", message, context) .WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerReportingUnsupportedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor SupportedDescriptor = new DiagnosticDescriptor("ID_1", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnsupportedDescriptor = new DiagnosticDescriptor("ID_2", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SupportedDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { try { ThrownException = null; compilationContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(UnsupportedDescriptor, Location.None)); } catch (Exception e) { ThrownException = e; throw; } }); } } [Fact, WorkItem(4376, "https://github.com/dotnet/roslyn/issues/4376")] public void TestReportingDiagnosticWithInvalidId() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithInvalidDiagnosticId() }; string message = new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticIdReported, AnalyzerWithInvalidDiagnosticId.Descriptor.Id), "diagnostic").Message; Exception analyzerException = null; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "Invalid ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticId", "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(30453, "https://github.com/dotnet/roslyn/issues/30453")] public void TestAnalyzerWithNullDescriptor() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNullDescriptor() }; var analyzerFullName = "Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithNullDescriptor"; string message = new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzerFullName), "SupportedDiagnostics").Message; Exception analyzerException = null; IFormattable context = $@"{new LazyToString(() => analyzerException)} -----"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments(analyzerFullName, "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithCSharpCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithCSharpCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CS101").WithLocation(1, 1)); } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithBasicCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithBasicCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("BC101").WithLocation(1, 1)); } [Theory, WorkItem(7173, "https://github.com/dotnet/roslyn/issues/7173")] [CombinatorialData] public void TestReportingDiagnosticWithInvalidLocation(AnalyzerWithInvalidDiagnosticLocation.ActionKind actionKind) { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var source2 = @"class C2 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var anotherCompilation = CreateCompilationWithMscorlib45(source2); var treeInAnotherCompilation = anotherCompilation.SyntaxTrees.Single(); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticLocationReported, AnalyzerWithInvalidDiagnosticLocation.Descriptor.Id, treeInAnotherCompilation.FilePath), "diagnostic").Message; compilation.VerifyDiagnostics(); var analyzer = new AnalyzerWithInvalidDiagnosticLocation(treeInAnotherCompilation, actionKind); var analyzers = new DiagnosticAnalyzer[] { analyzer }; Exception analyzerException = null; string contextDetail; switch (actionKind) { case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Symbol: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: C1 (NamedType)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CodeBlock: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method) SyntaxTree: SyntaxNode: void M() {{ int i = 0; i++; }} [MethodDeclarationSyntax]@[11..39) (0,11)-(0,39)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Operation: contextDetail = $@"Compilation: {compilation.AssemblyName} IOperation: VariableDeclarationGroup SyntaxTree: SyntaxNode: int i = 0; [LocalDeclarationStatementSyntax]@[22..32) (0,22)-(0,32)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.OperationBlockEnd: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Compilation: case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CompilationEnd: contextDetail = $@"Compilation: {compilation.AssemblyName}"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.SyntaxTree: contextDetail = $@"Compilation: {compilation.AssemblyName} SyntaxTree: "; break; default: throw ExceptionUtilities.Unreachable; } IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, contextDetail)} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticLocation", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact] public void TestReportingDiagnosticWithInvalidSpan() { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var treeInAnotherCompilation = compilation.SyntaxTrees.Single(); var badSpan = new Text.TextSpan(100000, 10000); var analyzer = new AnalyzerWithInvalidDiagnosticSpan(badSpan); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticSpanReported, AnalyzerWithInvalidDiagnosticSpan.Descriptor.Id, badSpan, treeInAnotherCompilation.FilePath), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName} SyntaxTree: ")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticSpan", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } [Fact, WorkItem(1473, "https://github.com/dotnet/roslyn/issues/1473")] public void TestReportingNotConfigurableDiagnostic() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new NotConfigurableDiagnosticAnalyzer() }; // Verify, not configurable enabled diagnostic is always reported and disabled diagnostic is never reported.. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable enabled diagnostic cannot be suppressed. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id, ReportDiagnostic.Suppress); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable disabled diagnostic cannot be enabled. specificDiagOptions.Clear(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.DisabledRule.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17), Diagnostic(CodeBlockActionAnalyzer.CodeBlockPerCompilationRule.Id, "M").WithArguments("M").WithLocation(4, 17) }); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction_OnlyStatelessAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer(onlyStatelessAction: true) }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17)); } [Fact, WorkItem(2614, "https://github.com/dotnet/roslyn/issues/2614")] public void TestGenericName() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; TestGenericNameCore(source, new CSharpGenericNameAnalyzer()); } private void TestGenericNameCore(string source, params DiagnosticAnalyzer[] analyzers) { // Verify, no duplicate diagnostics on generic name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpGenericNameAnalyzer.DiagnosticId, @"Nullable<int>").WithLocation(9, 17)); } [Fact, WorkItem(4745, "https://github.com/dotnet/roslyn/issues/4745")] public void TestNamespaceDeclarationAnalyzer() { var source = @" namespace Goo.Bar.GooBar { } "; var analyzers = new DiagnosticAnalyzer[] { new CSharpNamespaceDeclarationAnalyzer() }; // Verify, no duplicate diagnostics on qualified name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpNamespaceDeclarationAnalyzer.DiagnosticId, @"namespace Goo.Bar.GooBar { }").WithLocation(2, 1)); } [Fact, WorkItem(2980, "https://github.com/dotnet/roslyn/issues/2980")] public void TestAnalyzerWithNoActions() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; // Ensure that adding a dummy analyzer with no actions doesn't bring down entire analysis. // See https://github.com/dotnet/roslyn/issues/2980 for details. TestGenericNameCore(source, new AnalyzerWithNoActions(), new CSharpGenericNameAnalyzer()); } [Fact, WorkItem(4055, "https://github.com/dotnet/roslyn/issues/4055")] public void TestAnalyzerWithNoSupportedDiagnostics() { var source = @" class MyClass { }"; // Ensure that adding a dummy analyzer with no supported diagnostics doesn't bring down entire analysis. var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNoSupportedDiagnostics() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } private static void TestEffectiveSeverity( DiagnosticSeverity defaultSeverity, ReportDiagnostic expectedEffectiveSeverity, Dictionary<string, ReportDiagnostic> specificOptions = null, ReportDiagnostic generalOption = ReportDiagnostic.Default, bool isEnabledByDefault = true) { specificOptions = specificOptions ?? new Dictionary<string, ReportDiagnostic>(); var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, generalDiagnosticOption: generalOption, specificDiagnosticOptions: specificOptions); var descriptor = new DiagnosticDescriptor(id: "Test0001", title: "Test0001", messageFormat: "Test0001", category: "Test0001", defaultSeverity: defaultSeverity, isEnabledByDefault: isEnabledByDefault); var effectiveSeverity = descriptor.GetEffectiveSeverity(options); Assert.Equal(expectedEffectiveSeverity, effectiveSeverity); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault1() { TestEffectiveSeverity(DiagnosticSeverity.Warning, ReportDiagnostic.Warn); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault2() { var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", ReportDiagnostic.Default } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Warn, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOption() { var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: generalOption, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOption() { var specificOption = ReportDiagnostic.Suppress; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOptionDoesNotEnableDisabledDiagnostic() { var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Suppress, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact()] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOptionEnablesDisabledDiagnostic() { var specificOption = ReportDiagnostic.Warn; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact, WorkItem(5463, "https://github.com/dotnet/roslyn/issues/5463")] public void TestObjectCreationInCodeBlockAnalyzer() { string source = @" class C { } class D { public C x = new C(); }"; var analyzers = new DiagnosticAnalyzer[] { new CSharpCodeBlockObjectCreationAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CSharpCodeBlockObjectCreationAnalyzer.DiagnosticDescriptor.Id, "new C()").WithLocation(5, 18) }); } private static Compilation GetCompilationWithConcurrentBuildEnabled(string source) { var compilation = CreateCompilationWithMscorlib45(source); // NOTE: We set the concurrentBuild option to true after creating the compilation as CreateCompilationWithMscorlib // always sets concurrentBuild to false if debugger is attached, even if we had passed options with concurrentBuild = true to that API. // We want the tests using GetCompilationWithConcurrentBuildEnabled to have identical behavior with and without debugger being attached. var options = compilation.Options.WithConcurrentBuild(true); return compilation.WithOptions(options); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestNonConcurrentAnalyzer() { var builder = new StringBuilder(); var typeCount = 100; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var analyzers = new DiagnosticAnalyzer[] { new NonConcurrentAnalyzer() }; // Verify no diagnostics. var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestConcurrentAnalyzer() { if (Environment.ProcessorCount <= 1) { // Don't test for non-concurrent environment. return; } var builder = new StringBuilder(); var typeCount = 100; var typeNames = new string[typeCount]; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; typeNames[i - 1] = typeName; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics for Concurrent analyzer only. var analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames) }; var expected = new DiagnosticDescription[typeCount]; for (int i = 0; i < typeCount; i++) { var typeName = $"C{i + 1}"; expected[i] = Diagnostic(ConcurrentAnalyzer.Descriptor.Id, typeName) .WithArguments(typeName) .WithLocation(i + 2, 7); } compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); // Verify analyzer diagnostics for Concurrent and NonConcurrent analyzer together (latter reports diagnostics only for error cases). analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames), new NonConcurrentAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzer() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] class GeneratedCode{0} {{ private class Nested{0} {{ }} }} class NonGeneratedCode{0} {{ [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] private class NestedGeneratedCode{0} {{ }} }} "; var generatedFileNames = new List<string> { "TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs", "Test.designer.cs", "Test.Designer.cs", "Test.generated.cs", "Test.g.cs", "Test.g.i.cs" }; var builder = ImmutableArray.CreateBuilder<SyntaxTree>(); int treeNum = 0; // Trees with non-generated code file names var tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "SourceFileRegular.cs"); builder.Add(tree); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "AssemblyInfo.cs"); builder.Add(tree); // Trees with generated code file names foreach (var fileName in generatedFileNames) { tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: fileName); builder.Add(tree); } var autoGeneratedPrefixes = new[] { @"// <auto-generated>", @"// <autogenerated>", @"/* <auto-generated> */" }; for (var i = 0; i < autoGeneratedPrefixes.Length; i++) { // Tree with '<auto-generated>' comment var autoGeneratedPrefix = autoGeneratedPrefixes[i]; tree = CSharpSyntaxTree.ParseText(string.Format(autoGeneratedPrefix + source, treeNum++), path: $"SourceFileWithAutoGeneratedComment{i++}.cs"); builder.Add(tree); } // Files with editorconfig based "generated_code" configuration var analyzerConfigOptionsPerTreeBuilder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); // (1) "generated_code = true" const string myGeneratedFileTrueName = "MyGeneratedFileTrue.cs"; generatedFileNames.Add(myGeneratedFileTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileTrueName); builder.Add(tree); var analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "true")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (2) "generated_code = TRUE" (case insensitive) const string myGeneratedFileCaseInsensitiveTrueName = "MyGeneratedFileCaseInsensitiveTrue.cs"; generatedFileNames.Add(myGeneratedFileCaseInsensitiveTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileCaseInsensitiveTrueName); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "TRUE")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (3) "generated_code = false" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileFalse.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "false")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (4) "generated_code = auto" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileAuto.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "auto")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); var analyzerConfigOptionsProvider = new CompilerAnalyzerConfigOptionsProvider(analyzerConfigOptionsPerTreeBuilder.ToImmutable(), CompilerAnalyzerConfigOptions.Empty); var analyzerOptions = new AnalyzerOptions(additionalFiles: ImmutableArray<AdditionalText>.Empty, analyzerConfigOptionsProvider); // Verify no compiler diagnostics. var trees = builder.ToImmutable(); var compilation = CreateCompilationWithMscorlib45(trees, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); Func<string, bool> isGeneratedFile = fileName => fileName.Contains("SourceFileWithAutoGeneratedComment") || generatedFileNames.Contains(fileName); // (1) Verify default mode of analysis when there is no generated code configuration. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); // (2) Verify ConfigureGeneratedCodeAnalysis with different combinations of GeneratedCodeAnalysisFlags. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); // (4) Ensure warnaserror doesn't produce noise in generated files. var options = compilation.Options.WithGeneralDiagnosticOption(ReportDiagnostic.Error); var warnAsErrorCompilation = compilation.WithOptions(options); VerifyGeneratedCodeAnalyzerDiagnostics(warnAsErrorCompilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzerPartialType() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] partial class PartialType { } partial class PartialType { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "SourceFileRegular.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); // Expected symbol diagnostics var squiggledText = "PartialType"; var diagnosticArgument = squiggledText; var line = 3; var column = 15; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected tree diagnostics squiggledText = "}"; diagnosticArgument = tree.FilePath; line = 9; column = 1; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected compilation diagnostics AddExpectedNonLocalDiagnostic(builder, "PartialType", compilation.SyntaxTrees[0].FilePath); var expected = builder.ToArrayAndFree(); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt: null); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); } [Fact, WorkItem(11217, "https://github.com/dotnet/roslyn/issues/11217")] public void TestGeneratedCodeAnalyzerNoReportDiagnostics() { string source1 = @" class TypeInUserFile { } "; string source2 = @" class TypeInGeneratedFile { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "SourceFileRegular.cs"); var tree2 = CSharpSyntaxTree.ParseText(source2, path: "SourceFileRegular.Designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer2() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("GeneratedCodeAnalyzer2Warning", "TypeInUserFile").WithArguments("TypeInUserFile", "2").WithLocation(2, 7)); } internal class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if (nodeContext.ContainingSymbol.Name.StartsWith("Funky") && nodeContext.Compilation.Language == "C#") { nodeContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(ExpressionDescriptor, nodeContext.Node.GetLocation())); } }, SyntaxKind.IdentifierName, SyntaxKind.NumericLiteralExpression); } } [Fact] public void OwningSymbolTest() { const string source = @" class C { public void UnFunkyMethod() { int x = 0; int y = x; } public void FunkyMethod() { int x = 0; int y = x; } public int FunkyField = 12; public int UnFunkyField = 12; } "; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, AnalyzerOptions analyzerOptions, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var expected = GetExpectedGeneratedCodeAnalyzerDiagnostics(compilation, isGeneratedFileName, generatedCodeAnalysisFlagsOpt); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt, analyzerOptions); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, DiagnosticDescription[] expected, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, AnalyzerOptions analyzerOptions = null) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; compilation.VerifyAnalyzerDiagnostics(analyzers, analyzerOptions, null, expected: expected); } private static DiagnosticDescription[] GetExpectedGeneratedCodeAnalyzerDiagnostics(Compilation compilation, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; var files = compilation.SyntaxTrees.Select(t => t.FilePath).ToImmutableArray(); var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); for (int i = 0; i < compilation.SyntaxTrees.Count(); i++) { var file = files[i]; var isGeneratedFile = isGeneratedFileName(file); // Type "GeneratedCode{0}" var squiggledText = string.Format("GeneratedCode{0}", i); var diagnosticArgument = squiggledText; var line = 3; var column = 7; var isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "Nested{0}" squiggledText = string.Format("Nested{0}", i); diagnosticArgument = squiggledText; line = 5; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NonGeneratedCode{0}" squiggledText = string.Format("NonGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 8; column = 7; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NestedGeneratedCode{0}" squiggledText = string.Format("NestedGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 11; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // File diagnostic squiggledText = "}"; // last token in file. diagnosticArgument = file; line = 12; column = 1; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Compilation end summary diagnostic (verify callbacks into analyzer) // Analyzer always called for generated code, unless generated code analysis is explicitly disabled. if (generatedCodeAnalysisFlagsOpt == null || (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0) { sortedCallbackSymbolNames.Add(string.Format("GeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("Nested{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NestedGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } else if (!isGeneratedFile) { // Analyzer always called for non-generated code. sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } } // Compilation end summary diagnostic (verify callbacks into analyzer) var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); AddExpectedNonLocalDiagnostic(builder, arguments: new[] { arg1, arg2 }); if (compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) { for (int i = 0; i < builder.Count; i++) { if (((string)builder[i].Code) != GeneratedCodeAnalyzer.Error.Id) { builder[i] = builder[i].WithWarningAsError(true); } } } return builder.ToArrayAndFree(); } private static void AddExpectedLocalDiagnostics( ArrayBuilder<DiagnosticDescription> builder, bool isGeneratedCode, string squiggledText, int line, int column, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, params string[] arguments) { // Always report diagnostics in generated code, unless explicitly suppressed or we are not even analyzing generated code. var reportInGeneratedCode = generatedCodeAnalysisFlagsOpt == null || ((generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.ReportDiagnostics) != 0 && (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0); if (!isGeneratedCode || reportInGeneratedCode) { var diagnostic = Diagnostic(GeneratedCodeAnalyzer.Warning.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); diagnostic = Diagnostic(GeneratedCodeAnalyzer.Error.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } } private static void AddExpectedNonLocalDiagnostic(ArrayBuilder<DiagnosticDescription> builder, params string[] arguments) { AddExpectedDiagnostic(builder, GeneratedCodeAnalyzer.Summary.Id, squiggledText: null, line: 1, column: 1, arguments: arguments); } private static void AddExpectedDiagnostic(ArrayBuilder<DiagnosticDescription> builder, string diagnosticId, string squiggledText, int line, int column, params string[] arguments) { var diagnostic = Diagnostic(diagnosticId, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } [Fact] public void TestEnsureNoMergedNamespaceSymbolAnalyzer() { var source = @"namespace N1.N2 { }"; var metadataReference = CreateCompilation(source).ToMetadataReference(); var compilation = CreateCompilation(source, new[] { metadataReference }); compilation.VerifyDiagnostics(); // Analyzer reports a diagnostic if it receives a merged namespace symbol across assemblies in compilation. var analyzers = new DiagnosticAnalyzer[] { new EnsureNoMergedNamespaceSymbolAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6324, "https://github.com/dotnet/roslyn/issues/6324")] public void TestSharedStateAnalyzer() { string source1 = @" public partial class C { } "; string source2 = @" public partial class C2 { } "; string source3 = @" public partial class C33 { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File1.cs"); var tree2 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File2.cs"); var tree3 = CSharpSyntaxTree.ParseText(source2, path: "Source2_File3.cs"); var tree4 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File4.generated.cs"); var tree5 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File5.designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2, tree3, tree4, tree5 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SharedStateAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic", "C33").WithArguments("C33").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C2").WithArguments("C2").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C").WithArguments("C").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UserCodeDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("NumberOfUniqueTextFileDescriptor").WithArguments("3").WithLocation(1, 1)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InConstructor() { string source = @" public class C { public C(int a, int b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), Diagnostic("Parameter_ID", "b").WithLocation(4, 25)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InRegularMethod() { string source = @" public class C { void M1(string a, string b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 20), Diagnostic("Parameter_ID", "b").WithLocation(4, 30)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InIndexers() { string source = @" public class C { public int this[int index] { get { return 0; } set { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "index").WithLocation(4, 25)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_Lambdas() { string source = @" public class C { void M2() { System.Func<int, int, int> x = (int a, int b) => b; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Local_ID", "x").WithLocation(6, 36), Diagnostic("Parameter_ID", "a").WithLocation(6, 45), Diagnostic("Parameter_ID", "b").WithLocation(6, 52)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InAnonymousMethods() { string source = @" public class C { void M3() { M4(delegate (int x, int y) { }); } void M4(System.Action<int, int> a) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(9, 37), Diagnostic("Parameter_ID", "x").WithLocation(6, 26), Diagnostic("Parameter_ID", "y").WithLocation(6, 33)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InDelegateTypes() { string source = @" public class C { delegate void D(int x, string y); } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 25), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InOperators() { string source = @" public class C { public static implicit operator int (C c) { return 0; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(4, 44)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExplicitInterfaceImplementations() { string source = @" interface I { void M(int a, int b); } public class C : I { void I.M(int c, int d) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(9, 18), Diagnostic("Parameter_ID", "d").WithLocation(9, 25), Diagnostic("Parameter_ID", "a").WithLocation(4, 16), Diagnostic("Parameter_ID", "b").WithLocation(4, 23)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExtensionMethods() { string source = @" public static class C { static void M(this int x, int y) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 28), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InLocalFunctions() { string source = @" public class C { void M1() { M2(1, 2); void M2(int a, int b) { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), // ctor Diagnostic("Parameter_ID", "b").WithLocation(4, 25), Diagnostic("Local_ID", "c").WithLocation(6, 13), Diagnostic("Local_ID", "d").WithLocation(6, 20), Diagnostic("Parameter_ID", "a").WithLocation(10, 20), // M1 Diagnostic("Parameter_ID", "b").WithLocation(10, 30), Diagnostic("Local_ID", "c").WithLocation(12, 11), Diagnostic("Local_ID", "x").WithLocation(18, 36), // M2 Diagnostic("Parameter_ID", "a").WithLocation(26, 37), // M4 Diagnostic("Parameter_ID", "index").WithLocation(28, 25)); // indexer } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSymbolAnalyzer_HiddenRegions() { string source = @" #line hidden public class HiddenClass { } #line default public class RegularClass { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.None) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerError", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSyntaxAndOperationAnalyzer_HiddenRegions() { string source = @" public class Class { void DummyMethod(int i) { } #line hidden void HiddenMethod() { var hiddenVar = 0; DummyMethod(hiddenVar); } #line default void NonHiddenMethod() { var userVar = 0; DummyMethod(userVar); } void MixMethod() { #line hidden var mixMethodHiddenVar = 0; #line default var mixMethodUserVar = 0; DummyMethod(mixMethodHiddenVar + mixMethodUserVar); } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var syntaxKinds = ImmutableArray.Create(SyntaxKind.VariableDeclaration); var operationKinds = ImmutableArray.Create(OperationKind.VariableDeclarator); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.None, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var hiddenVar = 0").WithArguments("Node: var hiddenVar = 0").WithLocation(10, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "hiddenVar = 0").WithArguments("Operation: HiddenMethod").WithLocation(10, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodHiddenVar = 0").WithArguments("Node: var mixMethodHiddenVar = 0").WithLocation(24, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodHiddenVar = 0").WithArguments("Operation: MixMethod").WithLocation(24, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneratedCodeSyntaxAndOperationAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private readonly ImmutableArray<OperationKind> _operationKinds; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' entities", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, ImmutableArray<SyntaxKind> syntaxKinds, ImmutableArray<OperationKind> operationKinds) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; _syntaxKinds = syntaxKinds; _operationKinds = operationKinds; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackEntityNames = new SortedSet<string>(); context.RegisterSyntaxNodeAction(syntaxContext => { sortedCallbackEntityNames.Add($"Node: {syntaxContext.Node.ToString()}"); ReportNodeDiagnostics(syntaxContext.Node, syntaxContext.ReportDiagnostic); }, _syntaxKinds); context.RegisterOperationAction(operationContext => { sortedCallbackEntityNames.Add($"Operation: {operationContext.ContainingSymbol.Name}"); ReportOperationDiagnostics(operationContext.Operation, operationContext.ContainingSymbol.Name, operationContext.ReportDiagnostic); }, _operationKinds); context.RegisterCompilationEndAction(endContext => { // Summary diagnostic about received callbacks. var diagnostic = CodeAnalysis.Diagnostic.Create(Summary, Location.None, sortedCallbackEntityNames.Join(",")); endContext.ReportDiagnostic(diagnostic); }); } private void ReportNodeDiagnostics(SyntaxNode node, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, node.Location, $"Node: {node.ToString()}"); } private void ReportOperationDiagnostics(IOperation operation, string name, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, operation.Syntax.Location, $"Operation: {name}"); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = CodeAnalysis.Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InAttributes() { string source = @" using System; [assembly: MyAttribute(C.FieldForAssembly)] [module: MyAttribute(C.FieldForModule)] internal class MyAttribute : Attribute { public MyAttribute(int f) { } } internal interface MyInterface { event EventHandler MyEvent; } [MyAttribute(FieldForClass)] internal class C : MyInterface { internal const int FieldForClass = 1, FieldForStruct = 2, FieldForInterface = 3, FieldForField = 4, FieldForMethod = 5, FieldForEnum = 6, FieldForEnumMember = 7, FieldForDelegate = 8, FieldForEventField = 9, FieldForEvent = 10, FieldForAddHandler = 11, FieldForRemoveHandler = 12, FieldForProperty = 13, FieldForPropertyGetter = 14, FieldForPropertySetter = 15, FieldForIndexer = 16, FieldForIndexerGetter = 17, FieldForIndexerSetter = 18, FieldForExpressionBodiedMethod = 19, FieldForExpressionBodiedProperty = 20, FieldForMethodParameter = 21, FieldForDelegateParameter = 22, FieldForIndexerParameter = 23, FieldForMethodTypeParameter = 24, FieldForTypeTypeParameter = 25, FieldForDelegateTypeParameter = 26, FieldForMethodReturnType = 27, FieldForAssembly = 28, FieldForModule = 29, FieldForPropertyInitSetter = 30; [MyAttribute(FieldForStruct)] private struct S<[MyAttribute(FieldForTypeTypeParameter)] T> { } [MyAttribute(FieldForInterface)] private interface I { } [MyAttribute(FieldForField)] private int field2 = 0, field3 = 0; [return: MyAttribute(FieldForMethodReturnType)] [MyAttribute(FieldForMethod)] private void M1<[MyAttribute(FieldForMethodTypeParameter)]T>([MyAttribute(FieldForMethodParameter)]int p1) { } [MyAttribute(FieldForEnum)] private enum E { [MyAttribute(FieldForEnumMember)] F = 0 } [MyAttribute(FieldForDelegate)] public delegate void Delegate<[MyAttribute(FieldForDelegateTypeParameter)]T>([MyAttribute(FieldForDelegateParameter)]int p1); [MyAttribute(FieldForEventField)] public event Delegate<int> MyEvent; [MyAttribute(FieldForEvent)] event EventHandler MyInterface.MyEvent { [MyAttribute(FieldForAddHandler)] add { } [MyAttribute(FieldForRemoveHandler)] remove { } } [MyAttribute(FieldForProperty)] private int P1 { [MyAttribute(FieldForPropertyGetter)] get; [MyAttribute(FieldForPropertySetter)] set; } [MyAttribute(FieldForIndexer)] private int this[[MyAttribute(FieldForIndexerParameter)]int index] { [MyAttribute(FieldForIndexerGetter)] get { return 0; } [MyAttribute(FieldForIndexerSetter)] set { } } [MyAttribute(FieldForExpressionBodiedMethod)] private int M2 => 0; [MyAttribute(FieldForExpressionBodiedProperty)] private int P2 => 0; private int P3 { [MyAttribute(FieldForPropertyInitSetter)] init { } } } "; var compilation = CreateCompilationWithMscorlib45(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (51,32): warning CS0067: The event 'C.MyEvent' is never used // public event Delegate<int> MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("C.MyEvent").WithLocation(51, 32), // (34,17): warning CS0414: The field 'C.field2' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field2").WithArguments("C.field2").WithLocation(34, 17), // (34,29): warning CS0414: The field 'C.field3' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C.field3").WithLocation(34, 29)); // Test RegisterOperationBlockAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: false); static void testFieldReferenceAnalyzer_InAttributes_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "FieldForPropertyInitSetter").WithArguments("FieldForPropertyInitSetter", "30").WithLocation(92, 22), Diagnostic("ID", "FieldForClass").WithArguments("FieldForClass", "1").WithLocation(17, 14), Diagnostic("ID", "FieldForStruct").WithArguments("FieldForStruct", "2").WithLocation(27, 18), Diagnostic("ID", "FieldForInterface").WithArguments("FieldForInterface", "3").WithLocation(30, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForMethod").WithArguments("FieldForMethod", "5").WithLocation(37, 18), Diagnostic("ID", "FieldForEnum").WithArguments("FieldForEnum", "6").WithLocation(40, 18), Diagnostic("ID", "FieldForEnumMember").WithArguments("FieldForEnumMember", "7").WithLocation(43, 22), Diagnostic("ID", "FieldForDelegate").WithArguments("FieldForDelegate", "8").WithLocation(47, 18), Diagnostic("ID", "FieldForEventField").WithArguments("FieldForEventField", "9").WithLocation(50, 18), Diagnostic("ID", "FieldForEvent").WithArguments("FieldForEvent", "10").WithLocation(53, 18), Diagnostic("ID", "FieldForAddHandler").WithArguments("FieldForAddHandler", "11").WithLocation(56, 22), Diagnostic("ID", "FieldForRemoveHandler").WithArguments("FieldForRemoveHandler", "12").WithLocation(60, 22), Diagnostic("ID", "FieldForProperty").WithArguments("FieldForProperty", "13").WithLocation(66, 18), Diagnostic("ID", "FieldForPropertyGetter").WithArguments("FieldForPropertyGetter", "14").WithLocation(69, 22), Diagnostic("ID", "FieldForPropertySetter").WithArguments("FieldForPropertySetter", "15").WithLocation(71, 22), Diagnostic("ID", "FieldForIndexer").WithArguments("FieldForIndexer", "16").WithLocation(75, 18), Diagnostic("ID", "FieldForIndexerGetter").WithArguments("FieldForIndexerGetter", "17").WithLocation(78, 22), Diagnostic("ID", "FieldForIndexerSetter").WithArguments("FieldForIndexerSetter", "18").WithLocation(80, 22), Diagnostic("ID", "FieldForExpressionBodiedMethod").WithArguments("FieldForExpressionBodiedMethod", "19").WithLocation(84, 18), Diagnostic("ID", "FieldForExpressionBodiedProperty").WithArguments("FieldForExpressionBodiedProperty", "20").WithLocation(87, 18), Diagnostic("ID", "FieldForMethodParameter").WithArguments("FieldForMethodParameter", "21").WithLocation(38, 79), Diagnostic("ID", "FieldForDelegateParameter").WithArguments("FieldForDelegateParameter", "22").WithLocation(48, 95), Diagnostic("ID", "FieldForIndexerParameter").WithArguments("FieldForIndexerParameter", "23").WithLocation(76, 35), Diagnostic("ID", "FieldForMethodTypeParameter").WithArguments("FieldForMethodTypeParameter", "24").WithLocation(38, 34), Diagnostic("ID", "FieldForTypeTypeParameter").WithArguments("FieldForTypeTypeParameter", "25").WithLocation(28, 35), Diagnostic("ID", "FieldForDelegateTypeParameter").WithArguments("FieldForDelegateTypeParameter", "26").WithLocation(48, 48), Diagnostic("ID", "FieldForMethodReturnType").WithArguments("FieldForMethodReturnType", "27").WithLocation(36, 26), Diagnostic("ID", "C.FieldForAssembly").WithArguments("FieldForAssembly", "28").WithLocation(4, 24), Diagnostic("ID", "C.FieldForModule").WithArguments("FieldForModule", "29").WithLocation(5, 22)); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InConstructorInitializer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorInitializer_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Field").WithArguments("Field", "0").WithLocation(11, 29)); } [Fact, WorkItem(26520, "https://github.com/dotnet/roslyn/issues/26520")] public void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody() { string source = @" internal class C { public bool Flag; public C() => Flag = true; ~C() => Flag = false; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(5, 19), Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(6, 13)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M() { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithParameterInitializers() { string source = @" internal class A { public void M(int p = 0) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M(int p = 0) { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithExpressionAndMethodBody() { string source = @" internal class A { public int M() { return 0; } => 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public int M() { return 0; } => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int M() { return 0; } => 0;").WithLocation(4, 5)); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public int M() { return 0; } => 0;").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestConstructorBodyOperationAnalyzer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID", squiggledText: "protected Base(int i) { }").WithArguments(".ctor").WithLocation(4, 5), Diagnostic("ID", squiggledText: "public Derived() : base(Field) { }").WithArguments(".ctor").WithLocation(11, 5) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TestGetControlFlowGraphInOperationAnalyzers() { string source = @"class C { void M(int p = 0) { int x = 1 + 2; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (1,35): warning CS0219: The variable 'x' is assigned but its value is never used // class C { void M(int p = 0) { int x = 1 + 2; } } Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(1, 35)); var expectedFlowGraphs = new[] { // Method body @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, Constant: 3) (Syntax: '1 + 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)", // Parameter initializer @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 0') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)" }; // Verify analyzer diagnostics and flow graphs for different kind of operation analyzers. var analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.Operation, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("Operation").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("Operation").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("Operation").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationInOperationBlockStart, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("OperationInOperationBlockStart").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("OperationInOperationBlockStart").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("OperationInOperationBlockStart").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlock, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlock").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlockEnd, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlockEnd").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); void verifyFlowGraphs(ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> flowGraphs) { for (int i = 0; i < expectedFlowGraphs.Length; i++) { string expectedFlowGraph = expectedFlowGraphs[i]; (ControlFlowGraph actualFlowGraph, ISymbol associatedSymbol) = flowGraphs[i]; ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, actualFlowGraph, associatedSymbol); } } } private static void TestSymbolStartAnalyzerCore(SymbolStartAnalyzer analyzer, params DiagnosticDescription[] diagnostics) { TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer }, diagnostics); } private static void TestSymbolStartAnalyzerCore(DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { var source = @" #pragma warning disable CS0219 // unused local #pragma warning disable CS0067 // unused event class C1 { void M1() { int localInTypeInGlobalNamespace = 0; } } class C2 { class NestedType { void M2() { int localInNestedType = 0; } } } namespace N1 { } namespace N2 { namespace N3 { class C3 { void M3(int p) { int localInTypeInNamespace = 0; } void M4() { } } } } namespace N2.N3 { class C4 { public int f1 = 0; } } namespace N4 { class C5 { void M5() { } } class C6 { void M6() { } void M7() { } } } namespace N5 { partial class C7 { void M8() { } int P1 { get; set; } public event System.EventHandler e1; } partial class C7 { void M9() { } void M10() { } } } "; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); } [Fact] public void TestSymbolStartAnalyzer_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Field() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Field), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Property() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Property), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Event() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Event), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Parameter() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Parameter)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamespaceAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamedTypeAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_AllSymbolKinds() { testCore("SymbolStartTopLevelRuleId", topLevel: true); testCore("SymbolStartRuleId", topLevel: false); void testCore(string ruleId, bool topLevel) { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevel, symbolKinds[i], analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic(ruleId).WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Method, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_AllSymbolKinds() { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } [Fact] public void TestInitOnlyProperty() { string source1 = @" class C { int P1 { get; init; } int P2 { get; set; } }"; var compilation = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } var expected = new[] { Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("IsExternalInit", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P2", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("CompilerServices", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("Runtime", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("System", "Analyzer2").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestInvocationInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { M(); } private static void M() { } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.Invocation) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "M()", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestFieldReferenceInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { var x = _field; } private static int _field = 0; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.NamedType, OperationKind.FieldReference) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "_field", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(922802, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/922802")] public async Task TestAnalysisScopeForGetAnalyzerSemanticDiagnosticsAsync() { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 2); var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2)); // Invoke "GetAnalyzerSemanticDiagnosticsAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It should never force analyze the non-requested analyzer. // 2. It should only analyze the requested tree. If the requested tree has partial type declaration(s), // then it should also analyze additional trees with other partial declarations for partial types in the original tree, // but not other tree. var tree1SemanticDiagnostics = await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(semanticModel1, filterSpan: null, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1), CancellationToken.None); Assert.Equal(2, analyzer1.SymbolsStarted.Count); var sortedSymbolNames = analyzer1.SymbolsStarted.Select(s => s.Name).ToImmutableSortedSet(); Assert.Equal("_field1", sortedSymbolNames[0]); Assert.Equal("_field2", sortedSymbolNames[1]); Assert.Empty(analyzer2.SymbolsStarted); Assert.Empty(tree1SemanticDiagnostics); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_CompilationStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same diagnostics and callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A").WithLocation(1, 1) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithGloballySuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic for both files when specified globally var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }); Assert.Equal("", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for a single file when suppressed globally and un-suppressed for a single file options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress), (tree1, new[] { (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Default) }))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestConcurrentAnalyzerActions() { var first = AnalyzerActions.Empty; var second = AnalyzerActions.Empty; first.EnableConcurrentExecution(); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(first.Append(second).Concurrent); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(second.Append(first).Concurrent); } [Fact, WorkItem(41402, "https://github.com/dotnet/roslyn/issues/41402")] public async Task TestRegisterOperationBlockAndOperationActionOnSameContext() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Verify analyzer execution from command line // 'VerifyAnalyzerDiagnostics' helper executes the analyzers on the entire compilation without any state-based analysis. var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "M").WithLocation(4, 17)); // Now verify analyzer execution for a single file. // 'GetAnalyzerSemanticDiagnosticsAsync' executes the analyzers on the given file with state-based analysis. var model = compilation.GetSemanticModel(tree); var compWithAnalyzers = new CompilationWithAnalyzers( compilation, analyzers.ToImmutableArray(), new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty), CancellationToken.None); var diagnostics = await compWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(model, filterSpan: null, CancellationToken.None); diagnostics.Verify(Diagnostic("ID0001", "M").WithLocation(4, 17)); } [Fact, WorkItem(26217, "https://github.com/dotnet/roslyn/issues/26217")] public void TestConstructorInitializerWithExpressionBody() { string source = @" class C { C() : base() => _ = 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "C").WithLocation(4, 5)); } [Fact, WorkItem(43106, "https://github.com/dotnet/roslyn/issues/43106")] public void TestConstructorInitializerWithoutBody() { string source = @" class B { // Haven't typed { } on the next line yet public B() : this(1) public B(int a) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (5,12): error CS0501: 'B.B()' must declare a body because it is not marked abstract, extern, or partial // public B() : this(1) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "B").WithArguments("B.B()").WithLocation(5, 12), // (5,25): error CS1002: ; expected // public B() : this(1) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 25)); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID0001", "B").WithLocation(5, 12), Diagnostic("ID0001", "B").WithLocation(7, 12) }); } [Theory, CombinatorialData] public async Task TestGetAnalysisResultAsync(bool syntax, bool singleAnalyzer) { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var field1 = tree1.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single().Declaration.Variables.Single().Identifier; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new FieldAnalyzer("ID0001", syntax); var analyzer2 = new FieldAnalyzer("ID0002", syntax); var allAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var compilationWithAnalyzers = compilation.WithAnalyzers(allAnalyzers); // Invoke "GetAnalysisResultAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It only reports diagnostics for the requested analyzer. // 2. It only reports diagnostics for the requested tree. var analyzersToQuery = singleAnalyzer ? ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1) : allAnalyzers; AnalysisResult analysisResult; if (singleAnalyzer) { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, analyzersToQuery, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, analyzersToQuery, CancellationToken.None); } else { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, CancellationToken.None); } var diagnosticsMap = syntax ? analysisResult.SyntaxDiagnostics : analysisResult.SemanticDiagnostics; var diagnostics = diagnosticsMap.TryGetValue(tree1, out var value) ? value : ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>.Empty; foreach (var analyzer in allAnalyzers) { if (analyzersToQuery.Contains(analyzer)) { Assert.True(diagnostics.ContainsKey(analyzer)); var diagnostic = Assert.Single(diagnostics[analyzer]); Assert.Equal(((FieldAnalyzer)analyzer).Descriptor.Id, diagnostic.Id); Assert.Equal(field1.GetLocation(), diagnostic.Location); } else { Assert.False(diagnostics.ContainsKey(analyzer)); } } } [Theory, CombinatorialData] public async Task TestAdditionalFileAnalyzer(bool registerFromInitialize) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics(); AdditionalText additionalFile = new TestAdditionalText("Additional File Text"); var options = new AnalyzerOptions(ImmutableArray.Create(additionalFile)); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile, CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); void verifyDiagnostics(ImmutableArray<Diagnostic> diagnostics) { var diagnostic = Assert.Single(diagnostics); Assert.Equal(analyzer.Descriptor.Id, diagnostic.Id); Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(additionalFile.Path, location.FilePath); Assert.Equal(diagnosticSpan, location.SourceSpan); } } [Theory, CombinatorialData] public async Task TestMultipleAdditionalFileAnalyzers(bool registerFromInitialize, bool additionalFilesHaveSamePaths, bool firstAdditionalFileHasNullPath) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var path1 = firstAdditionalFileHasNullPath ? null : @"c:\file.txt"; var path2 = additionalFilesHaveSamePaths ? path1 : @"file2.txt"; AdditionalText additionalFile1 = new TestAdditionalText("Additional File1 Text", path: path1); AdditionalText additionalFile2 = new TestAdditionalText("Additional File2 Text", path: path2); var additionalFiles = ImmutableArray.Create(additionalFile1, additionalFile2); var options = new AnalyzerOptions(additionalFiles); var diagnosticSpan = new TextSpan(2, 2); var analyzer1 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0001"); var analyzer2 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0002"); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); var singleAnalyzerArray = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); if (!additionalFilesHaveSamePaths) { verifyAnalysisResult(analysisResult, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths, verifyGetAllDiagnostics: false); } return; static void verifyDiagnostics( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths) { foreach (AdditionalFileAnalyzer analyzer in analyzers) { var fileIndex = 0; foreach (var additionalFile in additionalFiles) { var applicableDiagnostics = diagnostics.WhereAsArray( d => d.Id == analyzer.Descriptor.Id && PathUtilities.Comparer.Equals(d.Location.GetLineSpan().Path, additionalFile.Path)); if (additionalFile.Path == null) { Assert.Empty(applicableDiagnostics); continue; } var expectedCount = additionalFilesHaveSamePaths ? additionalFiles.Length : 1; Assert.Equal(expectedCount, applicableDiagnostics.Length); foreach (var diagnostic in applicableDiagnostics) { Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(diagnosticSpan, location.SourceSpan); } fileIndex++; if (!additionalFilesHaveSamePaths || fileIndex == additionalFiles.Length) { diagnostics = diagnostics.RemoveRange(applicableDiagnostics); } } } Assert.Empty(diagnostics); } static void verifyAnalysisResult( AnalysisResult analysisResult, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths, bool verifyGetAllDiagnostics = true) { if (verifyGetAllDiagnostics) { verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); } foreach (var analyzer in analyzers) { var singleAnalyzerArray = ImmutableArray.Create(analyzer); foreach (var additionalFile in additionalFiles) { var reportedDiagnostics = getReportedDiagnostics(analysisResult, analyzer, additionalFile); verifyDiagnostics(reportedDiagnostics, singleAnalyzerArray, ImmutableArray.Create(additionalFile), diagnosticSpan, additionalFilesHaveSamePaths); } } return; static ImmutableArray<Diagnostic> getReportedDiagnostics(AnalysisResult analysisResult, DiagnosticAnalyzer analyzer, AdditionalText additionalFile) { if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFile, out var diagnosticsMap) && diagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { return diagnostics; } return ImmutableArray<Diagnostic>.Empty; } } } [Fact] public void TestSemanticModelProvider() { var tree = CSharpSyntaxTree.ParseText(@"class C { }"); Compilation compilation = CreateCompilation(new[] { tree }); var semanticModelProvider = new MySemanticModelProvider(); compilation = compilation.WithSemanticModelProvider(semanticModelProvider); // Verify semantic model provider is used by Compilation.GetSemanticModel API var model = compilation.GetSemanticModel(tree); semanticModelProvider.VerifyCachedModel(tree, model); // Verify semantic model provider is used by CSharpCompilation.GetSemanticModel API model = ((CSharpCompilation)compilation).GetSemanticModel(tree, ignoreAccessibility: false); semanticModelProvider.VerifyCachedModel(tree, model); } private sealed class MySemanticModelProvider : SemanticModelProvider { private readonly ConcurrentDictionary<SyntaxTree, SemanticModel> _cache = new ConcurrentDictionary<SyntaxTree, SemanticModel>(); public override SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false) { return _cache.GetOrAdd(tree, compilation.CreateSemanticModel(tree, ignoreAccessibility)); } public void VerifyCachedModel(SyntaxTree tree, SemanticModel model) { Assert.Same(model, _cache[tree]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests : CompilingTestBase { private class ComplainAboutX : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_CA9999_UseOfVariableThatStartsWithX = new DiagnosticDescriptor(id: "CA9999_UseOfVariableThatStartsWithX", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_CA9999_UseOfVariableThatStartsWithX); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.IdentifierName); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { var id = (IdentifierNameSyntax)context.Node; if (id.Identifier.ValueText.StartsWith("x", StringComparison.Ordinal)) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_CA9999_UseOfVariableThatStartsWithX, id.Location, id.Identifier.ValueText)); } } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTest() { string source = @"public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics( // (1,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (5,18): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (5,21): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (6,16): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTestInInitializer() { string source = @"delegate int D(out int x); public class C : NotFound { static int x1 = 2; static int x2 = 3; int x3 = x1 + x2; D d1 = (out int x4) => (x4 = 1) + @x4; }"; // TODO: Compilation create doesn't accept analyzers anymore. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,14): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (6,19): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (7,29): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x4").WithArguments("x4"), // (7,39): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "@x4").WithArguments("x4") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerSuppressDiagnostic() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); CreateCompilationWithMscorlib45(source, options: options/*, analyzers: new IDiagnosticAnalyzerFactory[] { new ComplainAboutX() }*/).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsError() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true) ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsErrorGlobal() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true)); } [Fact, WorkItem(1038025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038025")] public void TestImplicitlyDeclaredSymbolsNotAnalyzed() { string source = @" using System; public class C { public event EventHandler e; }"; CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ImplicitlyDeclaredSymbolAnalyzer() }); } private class SyntaxAndSymbolAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor("XX0001", "My Syntax/Symbol Diagnostic", "My Syntax/Symbol Diagnostic for '{0}'", "Compiler", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.Attribute, SyntaxKind.ClassDeclaration, SyntaxKind.UsingDirective); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.Attribute: var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "Attribute"); context.ReportDiagnostic(diag1); break; case SyntaxKind.ClassDeclaration: var diag2 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "ClassDeclaration"); context.ReportDiagnostic(diag2); break; case SyntaxKind.UsingDirective: var diag3 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "UsingDirective"); context.ReportDiagnostic(diag3); break; } } private void AnalyzeSymbol(SymbolAnalysisContext context) { var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Symbol.Locations[0], "NamedType"); context.ReportDiagnostic(diag1); } } [WorkItem(914236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/914236")] [Fact] public void DiagnosticAnalyzerSyntaxNodeAndSymbolAnalysis() { string source = @" using System; [Obsolete] public class C { }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SyntaxAndSymbolAnalyzer() }, null, null, // Symbol diagnostics Diagnostic("XX0001", "C").WithArguments("NamedType").WithWarningAsError(true), // Syntax diagnostics Diagnostic("XX0001", "using System;").WithArguments("UsingDirective").WithWarningAsError(true), // using directive Diagnostic("XX0001", "Obsolete").WithArguments("Attribute").WithWarningAsError(true), // attribute syntax Diagnostic("XX0001", @"[Obsolete] public class C { }").WithArguments("ClassDeclaration").WithWarningAsError(true)); // class declaration } [Fact] public void TestGetEffectiveDiagnostics() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; // Escalate all diagnostics to error. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); foreach (var effectiveDiag in effectiveDiags) { Assert.True(effectiveDiag.Severity == DiagnosticSeverity.Error); } // Suppress all diagnostics. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(0, effectiveDiags.Length); // Shuffle diagnostic severity. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Info); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Hidden); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); var diagIds = new HashSet<string>(diags.Select(d => d.Id)); foreach (var effectiveDiag in effectiveDiags) { Assert.True(diagIds.Remove(effectiveDiag.Id)); switch (effectiveDiag.Severity) { case DiagnosticSeverity.Hidden: Assert.Equal(infoDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Info: Assert.Equal(noneDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Warning: Assert.Equal(errorDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Error: Assert.Equal(warningDiagDescriptor.Id, effectiveDiag.Id); break; default: throw ExceptionUtilities.Unreachable; } } Assert.Empty(diagIds); } [Fact] public void TestGetEffectiveDiagnosticsGlobal() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = Microsoft.CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = Microsoft.CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = Microsoft.CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = Microsoft.CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Default); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.IsWarningAsError)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Warn); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Warning)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Info); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Info)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Hidden); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(2, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); } [Fact] public void TestDisabledDiagnostics() { var disabledDiagDescriptor = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); var enabledDiagDescriptor = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var disabledDiag = CodeAnalysis.Diagnostic.Create(disabledDiagDescriptor, Location.None); var enabledDiag = CodeAnalysis.Diagnostic.Create(enabledDiagDescriptor, Location.None); var diags = new[] { disabledDiag, enabledDiag }; // Verify that only the enabled diag shows up after filtering. var options = TestOptions.ReleaseDll; var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(enabledDiag, effectiveDiags); // If the disabled diag was enabled through options, then it should show up. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(disabledDiagDescriptor.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(enabledDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(disabledDiag, effectiveDiags); } internal class FullyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc3 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2, desc3); } } public override void Initialize(AnalysisContext context) { } } internal class PartiallyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2); } } public override void Initialize(AnalysisContext context) { } } internal class ImplicitlyDeclaredSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("DummyId", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction( (c) => { Assert.False(c.Symbol.IsImplicitlyDeclared); }, SymbolKind.Namespace, SymbolKind.NamedType, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } } [Fact] public void TestDisabledAnalyzers() { var fullyDisabledAnalyzer = new FullyDisabledAnalyzer(); var partiallyDisabledAnalyzer = new PartiallyDisabledAnalyzer(); var options = TestOptions.ReleaseDll; Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.False(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc1.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(PartiallyDisabledAnalyzer.desc2.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.False(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.True(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); // Verify not configurable disabled diagnostic cannot be enabled, and hence cannot affect IsDiagnosticAnalyzerSuppressed computation. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc3.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForNoExecutableCode() { string noExecutableCodeSource = @" public abstract class C { public int P { get; set; } public int field; public abstract int Method(); }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(noExecutableCodeSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForBaseConstructorInitializer() { string baseCtorSource = @" public class B { public B(int x) {} } public class C : B { public C() : base(x: 10) {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(baseCtorSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ConstructorInitializerDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic")); } [Fact, WorkItem(1067286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067286")] public void TestCodeBlockAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestSyntaxNodeAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: false) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestMethodSymbolAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new MethodSymbolAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.Property.get").WithLocation(4, 28), Diagnostic("MethodSymbolDiagnostic", "Method").WithArguments("B.Method()").WithLocation(5, 16), Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.this[int].get").WithLocation(6, 31)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FieldDeclarationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "MyFieldDiagnostic"; internal const string Title = "MyFieldDiagnostic"; internal const string MessageFormat = "MyFieldDiagnostic"; internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; var diagnostic = CodeAnalysis.Diagnostic.Create(Rule, fieldDeclaration.GetLocation()); context.ReportDiagnostic(diagnostic); } } [Fact] public void TestNoDuplicateCallbacksForFieldDeclaration() { string source = @" public class B { public string field = ""field""; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field = ""field"";").WithLocation(4, 5)); } [Fact, WorkItem(565, "https://github.com/dotnet/roslyn/issues/565")] public void TestCallbacksForFieldDeclarationWithMultipleVariables() { string source = @" public class B { public string field1, field2; public int field3 = 0, field4 = 1; public int field5, field6 = 1; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field1, field2;").WithLocation(4, 5), Diagnostic("MyFieldDiagnostic", @"public int field3 = 0, field4 = 1;").WithLocation(5, 5), Diagnostic("MyFieldDiagnostic", @"public int field5, field6 = 1;").WithLocation(6, 5)); } [Fact, WorkItem(1096600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096600")] public void TestDescriptorForConfigurableCompilerDiagnostics() { // Verify that all configurable compiler diagnostics, i.e. all non-error diagnostics, // have a non-null and non-empty Title and Category. // These diagnostic descriptor fields show up in the ruleset editor and hence must have a valid value. var analyzer = new CSharpCompilerDiagnosticAnalyzer(); foreach (var descriptor in analyzer.SupportedDiagnostics) { Assert.True(descriptor.IsEnabledByDefault); if (descriptor.IsNotConfigurable()) { continue; } var title = descriptor.Title.ToString(); if (string.IsNullOrEmpty(title)) { var id = Int32.Parse(descriptor.Id.Substring(2)); var missingResource = Enum.GetName(typeof(ErrorCode), id) + "_Title"; var message = string.Format("Add resource string named '{0}' for Title of '{1}' to '{2}'", missingResource, descriptor.Id, nameof(CSharpResources)); // This assert will fire if you are adding a new compiler diagnostic (non-error severity), // but did not add a title resource string for the diagnostic. Assert.True(false, message); } var category = descriptor.Category; if (string.IsNullOrEmpty(title)) { var message = string.Format("'{0}' must have a non-null non-empty 'Category'", descriptor.Id); Assert.True(false, message); } } } public class CodeBlockOrSyntaxNodeAnalyzer : DiagnosticAnalyzer { private readonly bool _isCodeBlockAnalyzer; public static DiagnosticDescriptor Descriptor1 = DescriptorFactory.CreateSimpleDescriptor("CodeBlockDiagnostic"); public static DiagnosticDescriptor Descriptor2 = DescriptorFactory.CreateSimpleDescriptor("EqualsValueDiagnostic"); public static DiagnosticDescriptor Descriptor3 = DescriptorFactory.CreateSimpleDescriptor("ConstructorInitializerDiagnostic"); public static DiagnosticDescriptor Descriptor4 = DescriptorFactory.CreateSimpleDescriptor("PropertyExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor5 = DescriptorFactory.CreateSimpleDescriptor("IndexerExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor6 = DescriptorFactory.CreateSimpleDescriptor("MethodExpressionBodyDiagnostic"); public CodeBlockOrSyntaxNodeAnalyzer(bool isCodeBlockAnalyzer) { _isCodeBlockAnalyzer = isCodeBlockAnalyzer; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2, Descriptor3, Descriptor4, Descriptor5, Descriptor6); } } public override void Initialize(AnalysisContext context) { if (_isCodeBlockAnalyzer) { context.RegisterCodeBlockStartAction<SyntaxKind>(OnCodeBlockStarted); context.RegisterCodeBlockAction(OnCodeBlockEnded); } else { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } } public static void OnCodeBlockEnded(CodeBlockAnalysisContext context) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, Location.None)); } public static void OnCodeBlockStarted(CodeBlockStartAnalysisContext<SyntaxKind> context) { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } protected class NodeAnalyzer { public void Initialize(Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerSyntaxNodeAction) { registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor2, Location.None)); }, ImmutableArray.Create(SyntaxKind.EqualsValueClause)); registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor3, Location.None)); }, ImmutableArray.Create(SyntaxKind.BaseConstructorInitializer)); registerSyntaxNodeAction(context => { var descriptor = (DiagnosticDescriptor)null; switch (CSharpExtensions.Kind(context.Node.Parent)) { case SyntaxKind.PropertyDeclaration: descriptor = Descriptor4; break; case SyntaxKind.IndexerDeclaration: descriptor = Descriptor5; break; default: descriptor = Descriptor6; break; } context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(descriptor, Location.None)); }, ImmutableArray.Create(SyntaxKind.ArrowExpressionClause)); } } } public class MethodSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor("MethodSymbolDiagnostic", "MethodSymbolDiagnostic", "{0}", "MethodSymbolDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(ctxt => { var method = ((IMethodSymbol)ctxt.Symbol); ctxt.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, method.Locations[0], method.ToDisplayString())); }, SymbolKind.Method); } } [Fact, WorkItem(252, "https://github.com/dotnet/roslyn/issues/252"), WorkItem(1392, "https://github.com/dotnet/roslyn/issues/1392")] public void TestReportingUnsupportedDiagnostic() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzer = new AnalyzerReportingUnsupportedDiagnostic(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; string message = new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedDiagnosticReported, AnalyzerReportingUnsupportedDiagnostic.UnsupportedDescriptor.Id), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID_1")}"; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CSharp.UnitTests.DiagnosticAnalyzerTests+AnalyzerReportingUnsupportedDiagnostic", "System.ArgumentException", message, context) .WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerReportingUnsupportedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor SupportedDescriptor = new DiagnosticDescriptor("ID_1", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnsupportedDescriptor = new DiagnosticDescriptor("ID_2", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SupportedDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { try { ThrownException = null; compilationContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(UnsupportedDescriptor, Location.None)); } catch (Exception e) { ThrownException = e; throw; } }); } } [Fact, WorkItem(4376, "https://github.com/dotnet/roslyn/issues/4376")] public void TestReportingDiagnosticWithInvalidId() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithInvalidDiagnosticId() }; string message = new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticIdReported, AnalyzerWithInvalidDiagnosticId.Descriptor.Id), "diagnostic").Message; Exception analyzerException = null; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "Invalid ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticId", "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(30453, "https://github.com/dotnet/roslyn/issues/30453")] public void TestAnalyzerWithNullDescriptor() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNullDescriptor() }; var analyzerFullName = "Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithNullDescriptor"; string message = new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzerFullName), "SupportedDiagnostics").Message; Exception analyzerException = null; IFormattable context = $@"{new LazyToString(() => analyzerException)} -----"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments(analyzerFullName, "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithCSharpCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithCSharpCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CS101").WithLocation(1, 1)); } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithBasicCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithBasicCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("BC101").WithLocation(1, 1)); } [Theory, WorkItem(7173, "https://github.com/dotnet/roslyn/issues/7173")] [CombinatorialData] public void TestReportingDiagnosticWithInvalidLocation(AnalyzerWithInvalidDiagnosticLocation.ActionKind actionKind) { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var source2 = @"class C2 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var anotherCompilation = CreateCompilationWithMscorlib45(source2); var treeInAnotherCompilation = anotherCompilation.SyntaxTrees.Single(); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticLocationReported, AnalyzerWithInvalidDiagnosticLocation.Descriptor.Id, treeInAnotherCompilation.FilePath), "diagnostic").Message; compilation.VerifyDiagnostics(); var analyzer = new AnalyzerWithInvalidDiagnosticLocation(treeInAnotherCompilation, actionKind); var analyzers = new DiagnosticAnalyzer[] { analyzer }; Exception analyzerException = null; string contextDetail; switch (actionKind) { case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Symbol: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: C1 (NamedType)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CodeBlock: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method) SyntaxTree: SyntaxNode: void M() {{ int i = 0; i++; }} [MethodDeclarationSyntax]@[11..39) (0,11)-(0,39)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Operation: contextDetail = $@"Compilation: {compilation.AssemblyName} IOperation: VariableDeclarationGroup SyntaxTree: SyntaxNode: int i = 0; [LocalDeclarationStatementSyntax]@[22..32) (0,22)-(0,32)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.OperationBlockEnd: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Compilation: case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CompilationEnd: contextDetail = $@"Compilation: {compilation.AssemblyName}"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.SyntaxTree: contextDetail = $@"Compilation: {compilation.AssemblyName} SyntaxTree: "; break; default: throw ExceptionUtilities.Unreachable; } IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, contextDetail)} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticLocation", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact] public void TestReportingDiagnosticWithInvalidSpan() { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var treeInAnotherCompilation = compilation.SyntaxTrees.Single(); var badSpan = new Text.TextSpan(100000, 10000); var analyzer = new AnalyzerWithInvalidDiagnosticSpan(badSpan); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticSpanReported, AnalyzerWithInvalidDiagnosticSpan.Descriptor.Id, badSpan, treeInAnotherCompilation.FilePath), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName} SyntaxTree: ")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticSpan", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } [Fact, WorkItem(1473, "https://github.com/dotnet/roslyn/issues/1473")] public void TestReportingNotConfigurableDiagnostic() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new NotConfigurableDiagnosticAnalyzer() }; // Verify, not configurable enabled diagnostic is always reported and disabled diagnostic is never reported.. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable enabled diagnostic cannot be suppressed. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id, ReportDiagnostic.Suppress); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable disabled diagnostic cannot be enabled. specificDiagOptions.Clear(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.DisabledRule.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17), Diagnostic(CodeBlockActionAnalyzer.CodeBlockPerCompilationRule.Id, "M").WithArguments("M").WithLocation(4, 17) }); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction_OnlyStatelessAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer(onlyStatelessAction: true) }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17)); } [Fact, WorkItem(2614, "https://github.com/dotnet/roslyn/issues/2614")] public void TestGenericName() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; TestGenericNameCore(source, new CSharpGenericNameAnalyzer()); } private void TestGenericNameCore(string source, params DiagnosticAnalyzer[] analyzers) { // Verify, no duplicate diagnostics on generic name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpGenericNameAnalyzer.DiagnosticId, @"Nullable<int>").WithLocation(9, 17)); } [Fact, WorkItem(4745, "https://github.com/dotnet/roslyn/issues/4745")] public void TestNamespaceDeclarationAnalyzer() { var source = @" namespace Goo.Bar.GooBar { } "; var analyzers = new DiagnosticAnalyzer[] { new CSharpNamespaceDeclarationAnalyzer() }; // Verify, no duplicate diagnostics on qualified name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpNamespaceDeclarationAnalyzer.DiagnosticId, @"namespace Goo.Bar.GooBar { }").WithLocation(2, 1)); } [Fact, WorkItem(2980, "https://github.com/dotnet/roslyn/issues/2980")] public void TestAnalyzerWithNoActions() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; // Ensure that adding a dummy analyzer with no actions doesn't bring down entire analysis. // See https://github.com/dotnet/roslyn/issues/2980 for details. TestGenericNameCore(source, new AnalyzerWithNoActions(), new CSharpGenericNameAnalyzer()); } [Fact, WorkItem(4055, "https://github.com/dotnet/roslyn/issues/4055")] public void TestAnalyzerWithNoSupportedDiagnostics() { var source = @" class MyClass { }"; // Ensure that adding a dummy analyzer with no supported diagnostics doesn't bring down entire analysis. var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNoSupportedDiagnostics() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } private static void TestEffectiveSeverity( DiagnosticSeverity defaultSeverity, ReportDiagnostic expectedEffectiveSeverity, Dictionary<string, ReportDiagnostic> specificOptions = null, ReportDiagnostic generalOption = ReportDiagnostic.Default, bool isEnabledByDefault = true) { specificOptions = specificOptions ?? new Dictionary<string, ReportDiagnostic>(); var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, generalDiagnosticOption: generalOption, specificDiagnosticOptions: specificOptions); var descriptor = new DiagnosticDescriptor(id: "Test0001", title: "Test0001", messageFormat: "Test0001", category: "Test0001", defaultSeverity: defaultSeverity, isEnabledByDefault: isEnabledByDefault); var effectiveSeverity = descriptor.GetEffectiveSeverity(options); Assert.Equal(expectedEffectiveSeverity, effectiveSeverity); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault1() { TestEffectiveSeverity(DiagnosticSeverity.Warning, ReportDiagnostic.Warn); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault2() { var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", ReportDiagnostic.Default } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Warn, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOption() { var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: generalOption, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOption() { var specificOption = ReportDiagnostic.Suppress; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOptionDoesNotEnableDisabledDiagnostic() { var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Suppress, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact()] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOptionEnablesDisabledDiagnostic() { var specificOption = ReportDiagnostic.Warn; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact, WorkItem(5463, "https://github.com/dotnet/roslyn/issues/5463")] public void TestObjectCreationInCodeBlockAnalyzer() { string source = @" class C { } class D { public C x = new C(); }"; var analyzers = new DiagnosticAnalyzer[] { new CSharpCodeBlockObjectCreationAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CSharpCodeBlockObjectCreationAnalyzer.DiagnosticDescriptor.Id, "new C()").WithLocation(5, 18) }); } private static Compilation GetCompilationWithConcurrentBuildEnabled(string source) { var compilation = CreateCompilationWithMscorlib45(source); // NOTE: We set the concurrentBuild option to true after creating the compilation as CreateCompilationWithMscorlib // always sets concurrentBuild to false if debugger is attached, even if we had passed options with concurrentBuild = true to that API. // We want the tests using GetCompilationWithConcurrentBuildEnabled to have identical behavior with and without debugger being attached. var options = compilation.Options.WithConcurrentBuild(true); return compilation.WithOptions(options); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestNonConcurrentAnalyzer() { var builder = new StringBuilder(); var typeCount = 100; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var analyzers = new DiagnosticAnalyzer[] { new NonConcurrentAnalyzer() }; // Verify no diagnostics. var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestConcurrentAnalyzer() { if (Environment.ProcessorCount <= 1) { // Don't test for non-concurrent environment. return; } var builder = new StringBuilder(); var typeCount = 100; var typeNames = new string[typeCount]; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; typeNames[i - 1] = typeName; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics for Concurrent analyzer only. var analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames) }; var expected = new DiagnosticDescription[typeCount]; for (int i = 0; i < typeCount; i++) { var typeName = $"C{i + 1}"; expected[i] = Diagnostic(ConcurrentAnalyzer.Descriptor.Id, typeName) .WithArguments(typeName) .WithLocation(i + 2, 7); } compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); // Verify analyzer diagnostics for Concurrent and NonConcurrent analyzer together (latter reports diagnostics only for error cases). analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames), new NonConcurrentAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzer() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] class GeneratedCode{0} {{ private class Nested{0} {{ }} }} class NonGeneratedCode{0} {{ [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] private class NestedGeneratedCode{0} {{ }} }} "; var generatedFileNames = new List<string> { "TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs", "Test.designer.cs", "Test.Designer.cs", "Test.generated.cs", "Test.g.cs", "Test.g.i.cs" }; var builder = ImmutableArray.CreateBuilder<SyntaxTree>(); int treeNum = 0; // Trees with non-generated code file names var tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "SourceFileRegular.cs"); builder.Add(tree); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "AssemblyInfo.cs"); builder.Add(tree); // Trees with generated code file names foreach (var fileName in generatedFileNames) { tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: fileName); builder.Add(tree); } var autoGeneratedPrefixes = new[] { @"// <auto-generated>", @"// <autogenerated>", @"/* <auto-generated> */" }; for (var i = 0; i < autoGeneratedPrefixes.Length; i++) { // Tree with '<auto-generated>' comment var autoGeneratedPrefix = autoGeneratedPrefixes[i]; tree = CSharpSyntaxTree.ParseText(string.Format(autoGeneratedPrefix + source, treeNum++), path: $"SourceFileWithAutoGeneratedComment{i++}.cs"); builder.Add(tree); } // Files with editorconfig based "generated_code" configuration var analyzerConfigOptionsPerTreeBuilder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); // (1) "generated_code = true" const string myGeneratedFileTrueName = "MyGeneratedFileTrue.cs"; generatedFileNames.Add(myGeneratedFileTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileTrueName); builder.Add(tree); var analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "true")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (2) "generated_code = TRUE" (case insensitive) const string myGeneratedFileCaseInsensitiveTrueName = "MyGeneratedFileCaseInsensitiveTrue.cs"; generatedFileNames.Add(myGeneratedFileCaseInsensitiveTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileCaseInsensitiveTrueName); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "TRUE")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (3) "generated_code = false" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileFalse.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "false")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (4) "generated_code = auto" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileAuto.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "auto")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); var analyzerConfigOptionsProvider = new CompilerAnalyzerConfigOptionsProvider(analyzerConfigOptionsPerTreeBuilder.ToImmutable(), CompilerAnalyzerConfigOptions.Empty); var analyzerOptions = new AnalyzerOptions(additionalFiles: ImmutableArray<AdditionalText>.Empty, analyzerConfigOptionsProvider); // Verify no compiler diagnostics. var trees = builder.ToImmutable(); var compilation = CreateCompilationWithMscorlib45(trees, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); Func<string, bool> isGeneratedFile = fileName => fileName.Contains("SourceFileWithAutoGeneratedComment") || generatedFileNames.Contains(fileName); // (1) Verify default mode of analysis when there is no generated code configuration. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); // (2) Verify ConfigureGeneratedCodeAnalysis with different combinations of GeneratedCodeAnalysisFlags. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); // (4) Ensure warnaserror doesn't produce noise in generated files. var options = compilation.Options.WithGeneralDiagnosticOption(ReportDiagnostic.Error); var warnAsErrorCompilation = compilation.WithOptions(options); VerifyGeneratedCodeAnalyzerDiagnostics(warnAsErrorCompilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzerPartialType() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] partial class PartialType { } partial class PartialType { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "SourceFileRegular.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); // Expected symbol diagnostics var squiggledText = "PartialType"; var diagnosticArgument = squiggledText; var line = 3; var column = 15; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected tree diagnostics squiggledText = "}"; diagnosticArgument = tree.FilePath; line = 9; column = 1; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected compilation diagnostics AddExpectedNonLocalDiagnostic(builder, "PartialType", compilation.SyntaxTrees[0].FilePath); var expected = builder.ToArrayAndFree(); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt: null); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); } [Fact, WorkItem(11217, "https://github.com/dotnet/roslyn/issues/11217")] public void TestGeneratedCodeAnalyzerNoReportDiagnostics() { string source1 = @" class TypeInUserFile { } "; string source2 = @" class TypeInGeneratedFile { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "SourceFileRegular.cs"); var tree2 = CSharpSyntaxTree.ParseText(source2, path: "SourceFileRegular.Designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer2() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("GeneratedCodeAnalyzer2Warning", "TypeInUserFile").WithArguments("TypeInUserFile", "2").WithLocation(2, 7)); } internal class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if (nodeContext.ContainingSymbol.Name.StartsWith("Funky") && nodeContext.Compilation.Language == "C#") { nodeContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(ExpressionDescriptor, nodeContext.Node.GetLocation())); } }, SyntaxKind.IdentifierName, SyntaxKind.NumericLiteralExpression); } } [Fact] public void OwningSymbolTest() { const string source = @" class C { public void UnFunkyMethod() { int x = 0; int y = x; } public void FunkyMethod() { int x = 0; int y = x; } public int FunkyField = 12; public int UnFunkyField = 12; } "; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, AnalyzerOptions analyzerOptions, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var expected = GetExpectedGeneratedCodeAnalyzerDiagnostics(compilation, isGeneratedFileName, generatedCodeAnalysisFlagsOpt); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt, analyzerOptions); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, DiagnosticDescription[] expected, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, AnalyzerOptions analyzerOptions = null) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; compilation.VerifyAnalyzerDiagnostics(analyzers, analyzerOptions, null, expected: expected); } private static DiagnosticDescription[] GetExpectedGeneratedCodeAnalyzerDiagnostics(Compilation compilation, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; var files = compilation.SyntaxTrees.Select(t => t.FilePath).ToImmutableArray(); var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); for (int i = 0; i < compilation.SyntaxTrees.Count(); i++) { var file = files[i]; var isGeneratedFile = isGeneratedFileName(file); // Type "GeneratedCode{0}" var squiggledText = string.Format("GeneratedCode{0}", i); var diagnosticArgument = squiggledText; var line = 3; var column = 7; var isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "Nested{0}" squiggledText = string.Format("Nested{0}", i); diagnosticArgument = squiggledText; line = 5; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NonGeneratedCode{0}" squiggledText = string.Format("NonGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 8; column = 7; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NestedGeneratedCode{0}" squiggledText = string.Format("NestedGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 11; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // File diagnostic squiggledText = "}"; // last token in file. diagnosticArgument = file; line = 12; column = 1; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Compilation end summary diagnostic (verify callbacks into analyzer) // Analyzer always called for generated code, unless generated code analysis is explicitly disabled. if (generatedCodeAnalysisFlagsOpt == null || (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0) { sortedCallbackSymbolNames.Add(string.Format("GeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("Nested{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NestedGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } else if (!isGeneratedFile) { // Analyzer always called for non-generated code. sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } } // Compilation end summary diagnostic (verify callbacks into analyzer) var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); AddExpectedNonLocalDiagnostic(builder, arguments: new[] { arg1, arg2 }); if (compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) { for (int i = 0; i < builder.Count; i++) { if (((string)builder[i].Code) != GeneratedCodeAnalyzer.Error.Id) { builder[i] = builder[i].WithWarningAsError(true); } } } return builder.ToArrayAndFree(); } private static void AddExpectedLocalDiagnostics( ArrayBuilder<DiagnosticDescription> builder, bool isGeneratedCode, string squiggledText, int line, int column, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, params string[] arguments) { // Always report diagnostics in generated code, unless explicitly suppressed or we are not even analyzing generated code. var reportInGeneratedCode = generatedCodeAnalysisFlagsOpt == null || ((generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.ReportDiagnostics) != 0 && (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0); if (!isGeneratedCode || reportInGeneratedCode) { var diagnostic = Diagnostic(GeneratedCodeAnalyzer.Warning.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); diagnostic = Diagnostic(GeneratedCodeAnalyzer.Error.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } } private static void AddExpectedNonLocalDiagnostic(ArrayBuilder<DiagnosticDescription> builder, params string[] arguments) { AddExpectedDiagnostic(builder, GeneratedCodeAnalyzer.Summary.Id, squiggledText: null, line: 1, column: 1, arguments: arguments); } private static void AddExpectedDiagnostic(ArrayBuilder<DiagnosticDescription> builder, string diagnosticId, string squiggledText, int line, int column, params string[] arguments) { var diagnostic = Diagnostic(diagnosticId, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } [Fact] public void TestEnsureNoMergedNamespaceSymbolAnalyzer() { var source = @"namespace N1.N2 { }"; var metadataReference = CreateCompilation(source).ToMetadataReference(); var compilation = CreateCompilation(source, new[] { metadataReference }); compilation.VerifyDiagnostics(); // Analyzer reports a diagnostic if it receives a merged namespace symbol across assemblies in compilation. var analyzers = new DiagnosticAnalyzer[] { new EnsureNoMergedNamespaceSymbolAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6324, "https://github.com/dotnet/roslyn/issues/6324")] public void TestSharedStateAnalyzer() { string source1 = @" public partial class C { } "; string source2 = @" public partial class C2 { } "; string source3 = @" public partial class C33 { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File1.cs"); var tree2 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File2.cs"); var tree3 = CSharpSyntaxTree.ParseText(source2, path: "Source2_File3.cs"); var tree4 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File4.generated.cs"); var tree5 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File5.designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2, tree3, tree4, tree5 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SharedStateAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic", "C33").WithArguments("C33").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C2").WithArguments("C2").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C").WithArguments("C").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UserCodeDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("NumberOfUniqueTextFileDescriptor").WithArguments("3").WithLocation(1, 1)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InConstructor() { string source = @" public class C { public C(int a, int b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), Diagnostic("Parameter_ID", "b").WithLocation(4, 25)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InRegularMethod() { string source = @" public class C { void M1(string a, string b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 20), Diagnostic("Parameter_ID", "b").WithLocation(4, 30)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InIndexers() { string source = @" public class C { public int this[int index] { get { return 0; } set { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "index").WithLocation(4, 25)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_Lambdas() { string source = @" public class C { void M2() { System.Func<int, int, int> x = (int a, int b) => b; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Local_ID", "x").WithLocation(6, 36), Diagnostic("Parameter_ID", "a").WithLocation(6, 45), Diagnostic("Parameter_ID", "b").WithLocation(6, 52)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InAnonymousMethods() { string source = @" public class C { void M3() { M4(delegate (int x, int y) { }); } void M4(System.Action<int, int> a) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(9, 37), Diagnostic("Parameter_ID", "x").WithLocation(6, 26), Diagnostic("Parameter_ID", "y").WithLocation(6, 33)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InDelegateTypes() { string source = @" public class C { delegate void D(int x, string y); } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 25), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InOperators() { string source = @" public class C { public static implicit operator int (C c) { return 0; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(4, 44)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExplicitInterfaceImplementations() { string source = @" interface I { void M(int a, int b); } public class C : I { void I.M(int c, int d) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(9, 18), Diagnostic("Parameter_ID", "d").WithLocation(9, 25), Diagnostic("Parameter_ID", "a").WithLocation(4, 16), Diagnostic("Parameter_ID", "b").WithLocation(4, 23)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExtensionMethods() { string source = @" public static class C { static void M(this int x, int y) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 28), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InLocalFunctions() { string source = @" public class C { void M1() { M2(1, 2); void M2(int a, int b) { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), // ctor Diagnostic("Parameter_ID", "b").WithLocation(4, 25), Diagnostic("Local_ID", "c").WithLocation(6, 13), Diagnostic("Local_ID", "d").WithLocation(6, 20), Diagnostic("Parameter_ID", "a").WithLocation(10, 20), // M1 Diagnostic("Parameter_ID", "b").WithLocation(10, 30), Diagnostic("Local_ID", "c").WithLocation(12, 11), Diagnostic("Local_ID", "x").WithLocation(18, 36), // M2 Diagnostic("Parameter_ID", "a").WithLocation(26, 37), // M4 Diagnostic("Parameter_ID", "index").WithLocation(28, 25)); // indexer } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSymbolAnalyzer_HiddenRegions() { string source = @" #line hidden public class HiddenClass { } #line default public class RegularClass { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.None) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerError", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSyntaxAndOperationAnalyzer_HiddenRegions() { string source = @" public class Class { void DummyMethod(int i) { } #line hidden void HiddenMethod() { var hiddenVar = 0; DummyMethod(hiddenVar); } #line default void NonHiddenMethod() { var userVar = 0; DummyMethod(userVar); } void MixMethod() { #line hidden var mixMethodHiddenVar = 0; #line default var mixMethodUserVar = 0; DummyMethod(mixMethodHiddenVar + mixMethodUserVar); } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var syntaxKinds = ImmutableArray.Create(SyntaxKind.VariableDeclaration); var operationKinds = ImmutableArray.Create(OperationKind.VariableDeclarator); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.None, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var hiddenVar = 0").WithArguments("Node: var hiddenVar = 0").WithLocation(10, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "hiddenVar = 0").WithArguments("Operation: HiddenMethod").WithLocation(10, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodHiddenVar = 0").WithArguments("Node: var mixMethodHiddenVar = 0").WithLocation(24, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodHiddenVar = 0").WithArguments("Operation: MixMethod").WithLocation(24, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneratedCodeSyntaxAndOperationAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private readonly ImmutableArray<OperationKind> _operationKinds; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' entities", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, ImmutableArray<SyntaxKind> syntaxKinds, ImmutableArray<OperationKind> operationKinds) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; _syntaxKinds = syntaxKinds; _operationKinds = operationKinds; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackEntityNames = new SortedSet<string>(); context.RegisterSyntaxNodeAction(syntaxContext => { sortedCallbackEntityNames.Add($"Node: {syntaxContext.Node.ToString()}"); ReportNodeDiagnostics(syntaxContext.Node, syntaxContext.ReportDiagnostic); }, _syntaxKinds); context.RegisterOperationAction(operationContext => { sortedCallbackEntityNames.Add($"Operation: {operationContext.ContainingSymbol.Name}"); ReportOperationDiagnostics(operationContext.Operation, operationContext.ContainingSymbol.Name, operationContext.ReportDiagnostic); }, _operationKinds); context.RegisterCompilationEndAction(endContext => { // Summary diagnostic about received callbacks. var diagnostic = CodeAnalysis.Diagnostic.Create(Summary, Location.None, sortedCallbackEntityNames.Join(",")); endContext.ReportDiagnostic(diagnostic); }); } private void ReportNodeDiagnostics(SyntaxNode node, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, node.Location, $"Node: {node.ToString()}"); } private void ReportOperationDiagnostics(IOperation operation, string name, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, operation.Syntax.Location, $"Operation: {name}"); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = CodeAnalysis.Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InAttributes() { string source = @" using System; [assembly: MyAttribute(C.FieldForAssembly)] [module: MyAttribute(C.FieldForModule)] internal class MyAttribute : Attribute { public MyAttribute(int f) { } } internal interface MyInterface { event EventHandler MyEvent; } [MyAttribute(FieldForClass)] internal class C : MyInterface { internal const int FieldForClass = 1, FieldForStruct = 2, FieldForInterface = 3, FieldForField = 4, FieldForMethod = 5, FieldForEnum = 6, FieldForEnumMember = 7, FieldForDelegate = 8, FieldForEventField = 9, FieldForEvent = 10, FieldForAddHandler = 11, FieldForRemoveHandler = 12, FieldForProperty = 13, FieldForPropertyGetter = 14, FieldForPropertySetter = 15, FieldForIndexer = 16, FieldForIndexerGetter = 17, FieldForIndexerSetter = 18, FieldForExpressionBodiedMethod = 19, FieldForExpressionBodiedProperty = 20, FieldForMethodParameter = 21, FieldForDelegateParameter = 22, FieldForIndexerParameter = 23, FieldForMethodTypeParameter = 24, FieldForTypeTypeParameter = 25, FieldForDelegateTypeParameter = 26, FieldForMethodReturnType = 27, FieldForAssembly = 28, FieldForModule = 29, FieldForPropertyInitSetter = 30; [MyAttribute(FieldForStruct)] private struct S<[MyAttribute(FieldForTypeTypeParameter)] T> { } [MyAttribute(FieldForInterface)] private interface I { } [MyAttribute(FieldForField)] private int field2 = 0, field3 = 0; [return: MyAttribute(FieldForMethodReturnType)] [MyAttribute(FieldForMethod)] private void M1<[MyAttribute(FieldForMethodTypeParameter)]T>([MyAttribute(FieldForMethodParameter)]int p1) { } [MyAttribute(FieldForEnum)] private enum E { [MyAttribute(FieldForEnumMember)] F = 0 } [MyAttribute(FieldForDelegate)] public delegate void Delegate<[MyAttribute(FieldForDelegateTypeParameter)]T>([MyAttribute(FieldForDelegateParameter)]int p1); [MyAttribute(FieldForEventField)] public event Delegate<int> MyEvent; [MyAttribute(FieldForEvent)] event EventHandler MyInterface.MyEvent { [MyAttribute(FieldForAddHandler)] add { } [MyAttribute(FieldForRemoveHandler)] remove { } } [MyAttribute(FieldForProperty)] private int P1 { [MyAttribute(FieldForPropertyGetter)] get; [MyAttribute(FieldForPropertySetter)] set; } [MyAttribute(FieldForIndexer)] private int this[[MyAttribute(FieldForIndexerParameter)]int index] { [MyAttribute(FieldForIndexerGetter)] get { return 0; } [MyAttribute(FieldForIndexerSetter)] set { } } [MyAttribute(FieldForExpressionBodiedMethod)] private int M2 => 0; [MyAttribute(FieldForExpressionBodiedProperty)] private int P2 => 0; private int P3 { [MyAttribute(FieldForPropertyInitSetter)] init { } } } "; var compilation = CreateCompilationWithMscorlib45(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (51,32): warning CS0067: The event 'C.MyEvent' is never used // public event Delegate<int> MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("C.MyEvent").WithLocation(51, 32), // (34,17): warning CS0414: The field 'C.field2' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field2").WithArguments("C.field2").WithLocation(34, 17), // (34,29): warning CS0414: The field 'C.field3' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C.field3").WithLocation(34, 29)); // Test RegisterOperationBlockAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: false); static void testFieldReferenceAnalyzer_InAttributes_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "FieldForPropertyInitSetter").WithArguments("FieldForPropertyInitSetter", "30").WithLocation(92, 22), Diagnostic("ID", "FieldForClass").WithArguments("FieldForClass", "1").WithLocation(17, 14), Diagnostic("ID", "FieldForStruct").WithArguments("FieldForStruct", "2").WithLocation(27, 18), Diagnostic("ID", "FieldForInterface").WithArguments("FieldForInterface", "3").WithLocation(30, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForMethod").WithArguments("FieldForMethod", "5").WithLocation(37, 18), Diagnostic("ID", "FieldForEnum").WithArguments("FieldForEnum", "6").WithLocation(40, 18), Diagnostic("ID", "FieldForEnumMember").WithArguments("FieldForEnumMember", "7").WithLocation(43, 22), Diagnostic("ID", "FieldForDelegate").WithArguments("FieldForDelegate", "8").WithLocation(47, 18), Diagnostic("ID", "FieldForEventField").WithArguments("FieldForEventField", "9").WithLocation(50, 18), Diagnostic("ID", "FieldForEvent").WithArguments("FieldForEvent", "10").WithLocation(53, 18), Diagnostic("ID", "FieldForAddHandler").WithArguments("FieldForAddHandler", "11").WithLocation(56, 22), Diagnostic("ID", "FieldForRemoveHandler").WithArguments("FieldForRemoveHandler", "12").WithLocation(60, 22), Diagnostic("ID", "FieldForProperty").WithArguments("FieldForProperty", "13").WithLocation(66, 18), Diagnostic("ID", "FieldForPropertyGetter").WithArguments("FieldForPropertyGetter", "14").WithLocation(69, 22), Diagnostic("ID", "FieldForPropertySetter").WithArguments("FieldForPropertySetter", "15").WithLocation(71, 22), Diagnostic("ID", "FieldForIndexer").WithArguments("FieldForIndexer", "16").WithLocation(75, 18), Diagnostic("ID", "FieldForIndexerGetter").WithArguments("FieldForIndexerGetter", "17").WithLocation(78, 22), Diagnostic("ID", "FieldForIndexerSetter").WithArguments("FieldForIndexerSetter", "18").WithLocation(80, 22), Diagnostic("ID", "FieldForExpressionBodiedMethod").WithArguments("FieldForExpressionBodiedMethod", "19").WithLocation(84, 18), Diagnostic("ID", "FieldForExpressionBodiedProperty").WithArguments("FieldForExpressionBodiedProperty", "20").WithLocation(87, 18), Diagnostic("ID", "FieldForMethodParameter").WithArguments("FieldForMethodParameter", "21").WithLocation(38, 79), Diagnostic("ID", "FieldForDelegateParameter").WithArguments("FieldForDelegateParameter", "22").WithLocation(48, 95), Diagnostic("ID", "FieldForIndexerParameter").WithArguments("FieldForIndexerParameter", "23").WithLocation(76, 35), Diagnostic("ID", "FieldForMethodTypeParameter").WithArguments("FieldForMethodTypeParameter", "24").WithLocation(38, 34), Diagnostic("ID", "FieldForTypeTypeParameter").WithArguments("FieldForTypeTypeParameter", "25").WithLocation(28, 35), Diagnostic("ID", "FieldForDelegateTypeParameter").WithArguments("FieldForDelegateTypeParameter", "26").WithLocation(48, 48), Diagnostic("ID", "FieldForMethodReturnType").WithArguments("FieldForMethodReturnType", "27").WithLocation(36, 26), Diagnostic("ID", "C.FieldForAssembly").WithArguments("FieldForAssembly", "28").WithLocation(4, 24), Diagnostic("ID", "C.FieldForModule").WithArguments("FieldForModule", "29").WithLocation(5, 22)); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InConstructorInitializer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorInitializer_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Field").WithArguments("Field", "0").WithLocation(11, 29)); } [Fact, WorkItem(26520, "https://github.com/dotnet/roslyn/issues/26520")] public void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody() { string source = @" internal class C { public bool Flag; public C() => Flag = true; ~C() => Flag = false; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(5, 19), Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(6, 13)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M() { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithParameterInitializers() { string source = @" internal class A { public void M(int p = 0) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M(int p = 0) { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithExpressionAndMethodBody() { string source = @" internal class A { public int M() { return 0; } => 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public int M() { return 0; } => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int M() { return 0; } => 0;").WithLocation(4, 5)); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public int M() { return 0; } => 0;").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestConstructorBodyOperationAnalyzer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID", squiggledText: "protected Base(int i) { }").WithArguments(".ctor").WithLocation(4, 5), Diagnostic("ID", squiggledText: "public Derived() : base(Field) { }").WithArguments(".ctor").WithLocation(11, 5) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TestGetControlFlowGraphInOperationAnalyzers() { string source = @"class C { void M(int p = 0) { int x = 1 + 2; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (1,35): warning CS0219: The variable 'x' is assigned but its value is never used // class C { void M(int p = 0) { int x = 1 + 2; } } Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(1, 35)); var expectedFlowGraphs = new[] { // Method body @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, Constant: 3) (Syntax: '1 + 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)", // Parameter initializer @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 0') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)" }; // Verify analyzer diagnostics and flow graphs for different kind of operation analyzers. var analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.Operation, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("Operation").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("Operation").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("Operation").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationInOperationBlockStart, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("OperationInOperationBlockStart").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("OperationInOperationBlockStart").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("OperationInOperationBlockStart").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlock, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlock").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlockEnd, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlockEnd").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); void verifyFlowGraphs(ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> flowGraphs) { for (int i = 0; i < expectedFlowGraphs.Length; i++) { string expectedFlowGraph = expectedFlowGraphs[i]; (ControlFlowGraph actualFlowGraph, ISymbol associatedSymbol) = flowGraphs[i]; ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, actualFlowGraph, associatedSymbol); } } } private static void TestSymbolStartAnalyzerCore(SymbolStartAnalyzer analyzer, params DiagnosticDescription[] diagnostics) { TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer }, diagnostics); } private static void TestSymbolStartAnalyzerCore(DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { var source = @" #pragma warning disable CS0219 // unused local #pragma warning disable CS0067 // unused event class C1 { void M1() { int localInTypeInGlobalNamespace = 0; } } class C2 { class NestedType { void M2() { int localInNestedType = 0; } } } namespace N1 { } namespace N2 { namespace N3 { class C3 { void M3(int p) { int localInTypeInNamespace = 0; } void M4() { } } } } namespace N2.N3 { class C4 { public int f1 = 0; } } namespace N4 { class C5 { void M5() { } } class C6 { void M6() { } void M7() { } } } namespace N5 { partial class C7 { void M8() { } int P1 { get; set; } public event System.EventHandler e1; } partial class C7 { void M9() { } void M10() { } } } "; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); } [Fact] public void TestSymbolStartAnalyzer_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Field() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Field), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Property() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Property), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Event() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Event), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Parameter() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Parameter)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamespaceAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamedTypeAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_AllSymbolKinds() { testCore("SymbolStartTopLevelRuleId", topLevel: true); testCore("SymbolStartRuleId", topLevel: false); void testCore(string ruleId, bool topLevel) { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevel, symbolKinds[i], analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic(ruleId).WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Method, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_AllSymbolKinds() { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } [Fact] public void TestInitOnlyProperty() { string source1 = @" class C { int P1 { get; init; } int P2 { get; set; } }"; var compilation = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } var expected = new[] { Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("IsExternalInit", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P2", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("CompilerServices", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("Runtime", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("System", "Analyzer2").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestInvocationInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { M(); } private static void M() { } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.Invocation) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "M()", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestFieldReferenceInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { var x = _field; } private static int _field = 0; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.NamedType, OperationKind.FieldReference) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "_field", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(922802, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/922802")] public async Task TestAnalysisScopeForGetAnalyzerSemanticDiagnosticsAsync() { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 2); var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2)); // Invoke "GetAnalyzerSemanticDiagnosticsAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It should never force analyze the non-requested analyzer. // 2. It should only analyze the requested tree. If the requested tree has partial type declaration(s), // then it should also analyze additional trees with other partial declarations for partial types in the original tree, // but not other tree. var tree1SemanticDiagnostics = await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(semanticModel1, filterSpan: null, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1), CancellationToken.None); Assert.Equal(2, analyzer1.SymbolsStarted.Count); var sortedSymbolNames = analyzer1.SymbolsStarted.Select(s => s.Name).ToImmutableSortedSet(); Assert.Equal("_field1", sortedSymbolNames[0]); Assert.Equal("_field2", sortedSymbolNames[1]); Assert.Empty(analyzer2.SymbolsStarted); Assert.Empty(tree1SemanticDiagnostics); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_CompilationStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same diagnostics and callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A").WithLocation(1, 1) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithGloballySuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic for both files when specified globally var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }); Assert.Equal("", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for a single file when suppressed globally and un-suppressed for a single file options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress), (tree1, new[] { (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Default) }))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestConcurrentAnalyzerActions() { var first = AnalyzerActions.Empty; var second = AnalyzerActions.Empty; first.EnableConcurrentExecution(); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(first.Append(second).Concurrent); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(second.Append(first).Concurrent); } [Fact, WorkItem(41402, "https://github.com/dotnet/roslyn/issues/41402")] public async Task TestRegisterOperationBlockAndOperationActionOnSameContext() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Verify analyzer execution from command line // 'VerifyAnalyzerDiagnostics' helper executes the analyzers on the entire compilation without any state-based analysis. var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "M").WithLocation(4, 17)); // Now verify analyzer execution for a single file. // 'GetAnalyzerSemanticDiagnosticsAsync' executes the analyzers on the given file with state-based analysis. var model = compilation.GetSemanticModel(tree); var compWithAnalyzers = new CompilationWithAnalyzers( compilation, analyzers.ToImmutableArray(), new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty), CancellationToken.None); var diagnostics = await compWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(model, filterSpan: null, CancellationToken.None); diagnostics.Verify(Diagnostic("ID0001", "M").WithLocation(4, 17)); } [Fact, WorkItem(26217, "https://github.com/dotnet/roslyn/issues/26217")] public void TestConstructorInitializerWithExpressionBody() { string source = @" class C { C() : base() => _ = 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "C").WithLocation(4, 5)); } [Fact, WorkItem(43106, "https://github.com/dotnet/roslyn/issues/43106")] public void TestConstructorInitializerWithoutBody() { string source = @" class B { // Haven't typed { } on the next line yet public B() : this(1) public B(int a) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (5,12): error CS0501: 'B.B()' must declare a body because it is not marked abstract, extern, or partial // public B() : this(1) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "B").WithArguments("B.B()").WithLocation(5, 12), // (5,25): error CS1002: ; expected // public B() : this(1) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 25)); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID0001", "B").WithLocation(5, 12), Diagnostic("ID0001", "B").WithLocation(7, 12) }); } [Theory, CombinatorialData] public async Task TestGetAnalysisResultAsync(bool syntax, bool singleAnalyzer) { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var field1 = tree1.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single().Declaration.Variables.Single().Identifier; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new FieldAnalyzer("ID0001", syntax); var analyzer2 = new FieldAnalyzer("ID0002", syntax); var allAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var compilationWithAnalyzers = compilation.WithAnalyzers(allAnalyzers); // Invoke "GetAnalysisResultAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It only reports diagnostics for the requested analyzer. // 2. It only reports diagnostics for the requested tree. var analyzersToQuery = singleAnalyzer ? ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1) : allAnalyzers; AnalysisResult analysisResult; if (singleAnalyzer) { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, analyzersToQuery, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, analyzersToQuery, CancellationToken.None); } else { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, CancellationToken.None); } var diagnosticsMap = syntax ? analysisResult.SyntaxDiagnostics : analysisResult.SemanticDiagnostics; var diagnostics = diagnosticsMap.TryGetValue(tree1, out var value) ? value : ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>.Empty; foreach (var analyzer in allAnalyzers) { if (analyzersToQuery.Contains(analyzer)) { Assert.True(diagnostics.ContainsKey(analyzer)); var diagnostic = Assert.Single(diagnostics[analyzer]); Assert.Equal(((FieldAnalyzer)analyzer).Descriptor.Id, diagnostic.Id); Assert.Equal(field1.GetLocation(), diagnostic.Location); } else { Assert.False(diagnostics.ContainsKey(analyzer)); } } } [Theory, CombinatorialData] public async Task TestAdditionalFileAnalyzer(bool registerFromInitialize) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics(); AdditionalText additionalFile = new TestAdditionalText("Additional File Text"); var options = new AnalyzerOptions(ImmutableArray.Create(additionalFile)); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile, CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); void verifyDiagnostics(ImmutableArray<Diagnostic> diagnostics) { var diagnostic = Assert.Single(diagnostics); Assert.Equal(analyzer.Descriptor.Id, diagnostic.Id); Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(additionalFile.Path, location.FilePath); Assert.Equal(diagnosticSpan, location.SourceSpan); } } [Theory, CombinatorialData] public async Task TestMultipleAdditionalFileAnalyzers(bool registerFromInitialize, bool additionalFilesHaveSamePaths, bool firstAdditionalFileHasNullPath) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var path1 = firstAdditionalFileHasNullPath ? null : @"c:\file.txt"; var path2 = additionalFilesHaveSamePaths ? path1 : @"file2.txt"; AdditionalText additionalFile1 = new TestAdditionalText("Additional File1 Text", path: path1); AdditionalText additionalFile2 = new TestAdditionalText("Additional File2 Text", path: path2); var additionalFiles = ImmutableArray.Create(additionalFile1, additionalFile2); var options = new AnalyzerOptions(additionalFiles); var diagnosticSpan = new TextSpan(2, 2); var analyzer1 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0001"); var analyzer2 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0002"); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); var singleAnalyzerArray = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); if (!additionalFilesHaveSamePaths) { verifyAnalysisResult(analysisResult, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths, verifyGetAllDiagnostics: false); } return; static void verifyDiagnostics( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths) { foreach (AdditionalFileAnalyzer analyzer in analyzers) { var fileIndex = 0; foreach (var additionalFile in additionalFiles) { var applicableDiagnostics = diagnostics.WhereAsArray( d => d.Id == analyzer.Descriptor.Id && PathUtilities.Comparer.Equals(d.Location.GetLineSpan().Path, additionalFile.Path)); if (additionalFile.Path == null) { Assert.Empty(applicableDiagnostics); continue; } var expectedCount = additionalFilesHaveSamePaths ? additionalFiles.Length : 1; Assert.Equal(expectedCount, applicableDiagnostics.Length); foreach (var diagnostic in applicableDiagnostics) { Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(diagnosticSpan, location.SourceSpan); } fileIndex++; if (!additionalFilesHaveSamePaths || fileIndex == additionalFiles.Length) { diagnostics = diagnostics.RemoveRange(applicableDiagnostics); } } } Assert.Empty(diagnostics); } static void verifyAnalysisResult( AnalysisResult analysisResult, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths, bool verifyGetAllDiagnostics = true) { if (verifyGetAllDiagnostics) { verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); } foreach (var analyzer in analyzers) { var singleAnalyzerArray = ImmutableArray.Create(analyzer); foreach (var additionalFile in additionalFiles) { var reportedDiagnostics = getReportedDiagnostics(analysisResult, analyzer, additionalFile); verifyDiagnostics(reportedDiagnostics, singleAnalyzerArray, ImmutableArray.Create(additionalFile), diagnosticSpan, additionalFilesHaveSamePaths); } } return; static ImmutableArray<Diagnostic> getReportedDiagnostics(AnalysisResult analysisResult, DiagnosticAnalyzer analyzer, AdditionalText additionalFile) { if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFile, out var diagnosticsMap) && diagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { return diagnostics; } return ImmutableArray<Diagnostic>.Empty; } } } [Fact] public void TestSemanticModelProvider() { var tree = CSharpSyntaxTree.ParseText(@"class C { }"); Compilation compilation = CreateCompilation(new[] { tree }); var semanticModelProvider = new MySemanticModelProvider(); compilation = compilation.WithSemanticModelProvider(semanticModelProvider); // Verify semantic model provider is used by Compilation.GetSemanticModel API var model = compilation.GetSemanticModel(tree); semanticModelProvider.VerifyCachedModel(tree, model); // Verify semantic model provider is used by CSharpCompilation.GetSemanticModel API model = ((CSharpCompilation)compilation).GetSemanticModel(tree, ignoreAccessibility: false); semanticModelProvider.VerifyCachedModel(tree, model); } private sealed class MySemanticModelProvider : SemanticModelProvider { private readonly ConcurrentDictionary<SyntaxTree, SemanticModel> _cache = new ConcurrentDictionary<SyntaxTree, SemanticModel>(); public override SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false) { return _cache.GetOrAdd(tree, compilation.CreateSemanticModel(tree, ignoreAccessibility)); } public void VerifyCachedModel(SyntaxTree tree, SemanticModel model) { Assert.Same(model, _cache[tree]); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Errors/XmlParseErrorCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum XmlParseErrorCode { XML_RefUndefinedEntity_1, XML_InvalidCharEntity, XML_InvalidUnicodeChar, XML_InvalidWhitespace, XML_MissingEqualsAttribute, XML_StringLiteralNoStartQuote, XML_StringLiteralNoEndQuote, XML_StringLiteralNonAsciiQuote, XML_LessThanInAttributeValue, XML_IncorrectComment, XML_ElementTypeMatch, XML_DuplicateAttribute, XML_WhitespaceMissing, XML_EndTagNotExpected, XML_CDataEndTagNotAllowed, XML_EndTagExpected, XML_ExpectedIdentifier, XML_ExpectedEndOfTag, // This is the default case for when we find an unexpected token. It // does not correspond to any MSXML error. XML_InvalidToken, XML_ExpectedEndOfXml, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum XmlParseErrorCode { XML_RefUndefinedEntity_1, XML_InvalidCharEntity, XML_InvalidUnicodeChar, XML_InvalidWhitespace, XML_MissingEqualsAttribute, XML_StringLiteralNoStartQuote, XML_StringLiteralNoEndQuote, XML_StringLiteralNonAsciiQuote, XML_LessThanInAttributeValue, XML_IncorrectComment, XML_ElementTypeMatch, XML_DuplicateAttribute, XML_WhitespaceMissing, XML_EndTagNotExpected, XML_CDataEndTagNotAllowed, XML_EndTagExpected, XML_ExpectedIdentifier, XML_ExpectedEndOfTag, // This is the default case for when we find an unexpected token. It // does not correspond to any MSXML error. XML_InvalidToken, XML_ExpectedEndOfXml, } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.VisualStudio.InteractiveWindow; using System.Collections.Generic; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Language.Intellisense.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { internal class TestResetInteractive : ResetInteractive { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly bool _buildSucceeds; internal int BuildProjectCount { get; private set; } internal int CancelBuildProjectCount { get; private set; } internal ImmutableArray<string> References { get; set; } internal ImmutableArray<string> ReferenceSearchPaths { get; set; } internal ImmutableArray<string> SourceSearchPaths { get; set; } internal ImmutableArray<string> ProjectNamespaces { get; set; } internal ImmutableArray<string> NamespacesToImport { get; set; } internal InteractiveHostPlatform? Platform { get; set; } internal string ProjectDirectory { get; set; } public TestResetInteractive( IUIThreadOperationExecutor uiThreadOperationExecutor, IEditorOptionsFactoryService editorOptionsFactoryService, Func<string, string> createReference, Func<string, string> createImport, bool buildSucceeds) : base(editorOptionsFactoryService, createReference, createImport) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _buildSucceeds = buildSucceeds; } protected override void CancelBuildProject() { CancelBuildProjectCount++; } protected override Task<bool> BuildProjectAsync() { BuildProjectCount++; return Task.FromResult(_buildSucceeds); } protected override bool GetProjectProperties( out ImmutableArray<string> references, out ImmutableArray<string> referenceSearchPaths, out ImmutableArray<string> sourceSearchPaths, out ImmutableArray<string> projectNamespaces, out string projectDirectory, out InteractiveHostPlatform? platform) { references = References; referenceSearchPaths = ReferenceSearchPaths; sourceSearchPaths = SourceSearchPaths; projectNamespaces = ProjectNamespaces; projectDirectory = ProjectDirectory; platform = Platform; return true; } protected override IUIThreadOperationExecutor GetUIThreadOperationExecutor() { return _uiThreadOperationExecutor; } protected override Task<IEnumerable<string>> GetNamespacesToImportAsync(IEnumerable<string> namespacesToImport, IInteractiveWindow interactiveWindow) { return Task.FromResult((IEnumerable<string>)NamespacesToImport); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.VisualStudio.InteractiveWindow; using System.Collections.Generic; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Language.Intellisense.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { internal class TestResetInteractive : ResetInteractive { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly bool _buildSucceeds; internal int BuildProjectCount { get; private set; } internal int CancelBuildProjectCount { get; private set; } internal ImmutableArray<string> References { get; set; } internal ImmutableArray<string> ReferenceSearchPaths { get; set; } internal ImmutableArray<string> SourceSearchPaths { get; set; } internal ImmutableArray<string> ProjectNamespaces { get; set; } internal ImmutableArray<string> NamespacesToImport { get; set; } internal InteractiveHostPlatform? Platform { get; set; } internal string ProjectDirectory { get; set; } public TestResetInteractive( IUIThreadOperationExecutor uiThreadOperationExecutor, IEditorOptionsFactoryService editorOptionsFactoryService, Func<string, string> createReference, Func<string, string> createImport, bool buildSucceeds) : base(editorOptionsFactoryService, createReference, createImport) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _buildSucceeds = buildSucceeds; } protected override void CancelBuildProject() { CancelBuildProjectCount++; } protected override Task<bool> BuildProjectAsync() { BuildProjectCount++; return Task.FromResult(_buildSucceeds); } protected override bool GetProjectProperties( out ImmutableArray<string> references, out ImmutableArray<string> referenceSearchPaths, out ImmutableArray<string> sourceSearchPaths, out ImmutableArray<string> projectNamespaces, out string projectDirectory, out InteractiveHostPlatform? platform) { references = References; referenceSearchPaths = ReferenceSearchPaths; sourceSearchPaths = SourceSearchPaths; projectNamespaces = ProjectNamespaces; projectDirectory = ProjectDirectory; platform = Platform; return true; } protected override IUIThreadOperationExecutor GetUIThreadOperationExecutor() { return _uiThreadOperationExecutor; } protected override Task<IEnumerable<string>> GetNamespacesToImportAsync(IEnumerable<string> namespacesToImport, IInteractiveWindow interactiveWindow) { return Task.FromResult((IEnumerable<string>)NamespacesToImport); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicLineCommit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using ProjName = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicLineCommit : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicLineCommit(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicLineCommit)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CaseCorrection() { VisualStudio.Editor.SetText(@"Module Goo Sub M() Dim x = Sub() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Sub()", charsOffset: 1); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.Verify.CaretPosition(48); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void UndoWithEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub REM End Module"); VisualStudio.Editor.PlaceCaret(" REM"); VisualStudio.Editor.SendKeys("sub", VirtualKey.Escape, " goo()", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Sub goo() End Sub"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(54); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void UndoWithoutEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Module1"); VisualStudio.Editor.SendKeys(VirtualKey.Down, VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.Verify.CaretPosition(18); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(16); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnSave() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub End Module "); VisualStudio.Editor.PlaceCaret("(", charsOffset: 1); VisualStudio.Editor.SendKeys("x As integer", VirtualKey.Tab); VisualStudio.Editor.Verify.IsNotSaved(); VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Ctrl)); var savedFileName = VisualStudio.Editor.Verify.IsSaved(); try { VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); } catch (Exception e) { throw new InvalidOperationException($"Unexpected failure after saving document '{savedFileName}'", e); } VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); VisualStudio.Editor.Verify.CaretPosition(45); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnFocusLost() { VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseCodeFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnFocusLostDoesNotFormatWithPrettyListingOff() { try { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, false); VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseCodeFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } finally { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, true); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using ProjName = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicLineCommit : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicLineCommit(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicLineCommit)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CaseCorrection() { VisualStudio.Editor.SetText(@"Module Goo Sub M() Dim x = Sub() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Sub()", charsOffset: 1); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.Verify.CaretPosition(48); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void UndoWithEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub REM End Module"); VisualStudio.Editor.PlaceCaret(" REM"); VisualStudio.Editor.SendKeys("sub", VirtualKey.Escape, " goo()", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Sub goo() End Sub"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(54); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void UndoWithoutEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Module1"); VisualStudio.Editor.SendKeys(VirtualKey.Down, VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.Verify.CaretPosition(18); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(16); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnSave() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub End Module "); VisualStudio.Editor.PlaceCaret("(", charsOffset: 1); VisualStudio.Editor.SendKeys("x As integer", VirtualKey.Tab); VisualStudio.Editor.Verify.IsNotSaved(); VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Ctrl)); var savedFileName = VisualStudio.Editor.Verify.IsSaved(); try { VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); } catch (Exception e) { throw new InvalidOperationException($"Unexpected failure after saving document '{savedFileName}'", e); } VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); VisualStudio.Editor.Verify.CaretPosition(45); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnFocusLost() { VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseCodeFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } [WpfFact, Trait(Traits.Feature, Traits.Features.LineCommit)] private void CommitOnFocusLostDoesNotFormatWithPrettyListingOff() { try { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, false); VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseCodeFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } finally { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, true); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/TestUtilities/DocumentationComments/AbstractXmlTagCompletionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments { [UseExportProvider] public abstract class AbstractXmlTagCompletionTests { internal abstract IChainedCommandHandler<TypeCharCommandArgs> CreateCommandHandler(TestWorkspace testWorkspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); public void Verify(string initialMarkup, string expectedMarkup, char typeChar) { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = CreateCommandHandler(workspace); var args = new TypeCharCommandArgs(view, view.TextBuffer, typeChar); var nextHandler = CreateInsertTextHandler(view, typeChar.ToString()); commandHandler.ExecuteCommand(args, nextHandler, TestCommandExecutionContext.Create()); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length)); }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments { [UseExportProvider] public abstract class AbstractXmlTagCompletionTests { internal abstract IChainedCommandHandler<TypeCharCommandArgs> CreateCommandHandler(TestWorkspace testWorkspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); public void Verify(string initialMarkup, string expectedMarkup, char typeChar) { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = CreateCommandHandler(workspace); var args = new TypeCharCommandArgs(view, view.TextBuffer, typeChar); var nextHandler = CreateInsertTextHandler(view, typeChar.ToString()); commandHandler.ExecuteCommand(args, nextHandler, TestCommandExecutionContext.Create()); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length)); }; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Options/IOptionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. This will provide support for /// customizations workspaces need to perform around options. Note that /// <see cref="IGlobalOptionService"/> options will normally still be offered through /// implementations of this. However, implementations may customize things differently /// depending on their needs. /// </summary> internal interface IOptionService : IWorkspaceService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Fetches an immutable set of all current options. /// </summary> SerializableOptionSet GetOptions(); /// <summary> /// Gets a serializable option set snapshot with force computed values for all registered serializable options applicable for the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages); /// <summary> /// Applies a set of options. /// </summary> /// <param name="optionSet">New options to set.</param> void SetOptions(OptionSet optionSet); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <inheritdoc cref="IGlobalOptionService.TryMapEditorConfigKeyToOption"/> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs> OptionChanged; /// <summary> /// Registers a provider that can modify the result of <see cref="Document.GetOptionsAsync(CancellationToken)"/>. Providers registered earlier are queried first /// for options, and the first provider to give a value wins. /// </summary> void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider); /// <summary> /// Returns the <see cref="OptionSet"/> that applies to a specific document, given that document and the global options. /// </summary> Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. This will provide support for /// customizations workspaces need to perform around options. Note that /// <see cref="IGlobalOptionService"/> options will normally still be offered through /// implementations of this. However, implementations may customize things differently /// depending on their needs. /// </summary> internal interface IOptionService : IWorkspaceService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Fetches an immutable set of all current options. /// </summary> SerializableOptionSet GetOptions(); /// <summary> /// Gets a serializable option set snapshot with force computed values for all registered serializable options applicable for the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages); /// <summary> /// Applies a set of options. /// </summary> /// <param name="optionSet">New options to set.</param> void SetOptions(OptionSet optionSet); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <inheritdoc cref="IGlobalOptionService.TryMapEditorConfigKeyToOption"/> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs> OptionChanged; /// <summary> /// Registers a provider that can modify the result of <see cref="Document.GetOptionsAsync(CancellationToken)"/>. Providers registered earlier are queried first /// for options, and the first provider to give a value wins. /// </summary> void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider); /// <summary> /// Returns the <see cref="OptionSet"/> that applies to a specific document, given that document and the global options. /// </summary> Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VenusMargin/ProjectionSpanTagDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Roslyn.Hosting.Diagnostics.VenusMargin { [Export(typeof(EditorFormatDefinition))] [Name(ProjectionSpanTag.TagId)] internal class ProjectionSpanTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectionSpanTagDefinition() { this.Border = new Pen(Brushes.DarkBlue, thickness: 1.5); this.BackgroundColor = Colors.LightBlue; this.DisplayName = "Projection Span"; this.ZOrder = 10; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Roslyn.Hosting.Diagnostics.VenusMargin { [Export(typeof(EditorFormatDefinition))] [Name(ProjectionSpanTag.TagId)] internal class ProjectionSpanTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectionSpanTagDefinition() { this.Border = new Pen(Brushes.DarkBlue, thickness: 1.5); this.BackgroundColor = Colors.LightBlue; this.DisplayName = "Projection Span"; this.ZOrder = 10; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Completion/Providers/CompletionUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Recommendations; namespace Microsoft.CodeAnalysis.Completion.Providers { internal static class CompletionUtilities { public static bool IsTypeImplicitlyConvertible(Compilation compilation, ITypeSymbol sourceType, ImmutableArray<ITypeSymbol> targetTypes) { foreach (var targetType in targetTypes) { if (compilation.ClassifyCommonConversion(sourceType, targetType).IsImplicit) { return true; } } return false; } public static OptionSet GetUpdatedRecommendationOptions(OptionSet options, string language) { var filterOutOfScopeLocals = options.GetOption(CompletionControllerOptions.FilterOutOfScopeLocals); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers, language); return options .WithChangedOption(RecommendationOptions.FilterOutOfScopeLocals, language, filterOutOfScopeLocals) .WithChangedOption(RecommendationOptions.HideAdvancedMembers, language, hideAdvancedMembers); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Recommendations; namespace Microsoft.CodeAnalysis.Completion.Providers { internal static class CompletionUtilities { public static bool IsTypeImplicitlyConvertible(Compilation compilation, ITypeSymbol sourceType, ImmutableArray<ITypeSymbol> targetTypes) { foreach (var targetType in targetTypes) { if (compilation.ClassifyCommonConversion(sourceType, targetType).IsImplicit) { return true; } } return false; } public static OptionSet GetUpdatedRecommendationOptions(OptionSet options, string language) { var filterOutOfScopeLocals = options.GetOption(CompletionControllerOptions.FilterOutOfScopeLocals); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers, language); return options .WithChangedOption(RecommendationOptions.FilterOutOfScopeLocals, language, filterOutOfScopeLocals) .WithChangedOption(RecommendationOptions.HideAdvancedMembers, language, hideAdvancedMembers); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal abstract class AbstractGoToDefinitionHandler : AbstractStatelessRequestHandler<LSP.TextDocumentPositionParams, LSP.Location[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; public AbstractGoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) => _metadataAsSourceFileService = metadataAsSourceFileService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.TextDocumentPositionParams request) => request.TextDocument; protected async Task<LSP.Location[]> GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool typeOnly, RequestContext context, CancellationToken cancellationToken) { var locations = ArrayBuilder<LSP.Location>.GetInstance(); var document = context.Document; if (document == null) { return locations.ToArrayAndFree(); } var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var definitions = await GetDefinitions(document, position, cancellationToken).ConfigureAwait(false); if (definitions?.Any() == true) { foreach (var definition in definitions) { if (!ShouldInclude(definition, typeOnly)) { continue; } var location = await ProtocolConversions.TextSpanToLocationAsync( definition.Document, definition.SourceSpan, definition.IsStale, cancellationToken).ConfigureAwait(false); locations.AddIfNotNull(location); } } else if (document.SupportsSemanticModel && _metadataAsSourceFileService != null) { // No definition found - see if we can get metadata as source but that's only applicable for C#\VB. var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); if (symbol != null && !symbol.Locations.IsEmpty && symbol.Locations.First().IsInMetadata) { if (!typeOnly || symbol is ITypeSymbol) { var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync(document.Project, symbol, false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; locations.Add(new LSP.Location { Uri = new Uri(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }); } } } return locations.ToArrayAndFree(); // local functions static bool ShouldInclude(INavigableItem item, bool typeOnly) { if (item.Glyph is Glyph.Namespace) { // Never return namespace symbols as part of the go to definition result. return false; } if (!typeOnly) { return true; } switch (item.Glyph) { case Glyph.ClassPublic: case Glyph.ClassProtected: case Glyph.ClassPrivate: case Glyph.ClassInternal: case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: case Glyph.EnumPublic: case Glyph.EnumProtected: case Glyph.EnumPrivate: case Glyph.EnumInternal: case Glyph.EventPublic: case Glyph.EventProtected: case Glyph.EventPrivate: case Glyph.EventInternal: case Glyph.InterfacePublic: case Glyph.InterfaceProtected: case Glyph.InterfacePrivate: case Glyph.InterfaceInternal: case Glyph.ModulePublic: case Glyph.ModuleProtected: case Glyph.ModulePrivate: case Glyph.ModuleInternal: case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return true; default: return false; } } static async Task<IEnumerable<INavigableItem>?> GetDefinitions(Document document, int position, CancellationToken cancellationToken) { // Try IFindDefinitionService first. Until partners implement this, it could fail to find a service, so fall back if it's null. var findDefinitionService = document.GetLanguageService<IFindDefinitionService>(); if (findDefinitionService != null) { return await findDefinitionService.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); } // Removal of this codepath is tracked by https://github.com/dotnet/roslyn/issues/50391. var goToDefinitionsService = document.GetRequiredLanguageService<IGoToDefinitionService>(); return await goToDefinitionsService.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal abstract class AbstractGoToDefinitionHandler : AbstractStatelessRequestHandler<LSP.TextDocumentPositionParams, LSP.Location[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; public AbstractGoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) => _metadataAsSourceFileService = metadataAsSourceFileService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.TextDocumentPositionParams request) => request.TextDocument; protected async Task<LSP.Location[]> GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool typeOnly, RequestContext context, CancellationToken cancellationToken) { var locations = ArrayBuilder<LSP.Location>.GetInstance(); var document = context.Document; if (document == null) { return locations.ToArrayAndFree(); } var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var definitions = await GetDefinitions(document, position, cancellationToken).ConfigureAwait(false); if (definitions?.Any() == true) { foreach (var definition in definitions) { if (!ShouldInclude(definition, typeOnly)) { continue; } var location = await ProtocolConversions.TextSpanToLocationAsync( definition.Document, definition.SourceSpan, definition.IsStale, cancellationToken).ConfigureAwait(false); locations.AddIfNotNull(location); } } else if (document.SupportsSemanticModel && _metadataAsSourceFileService != null) { // No definition found - see if we can get metadata as source but that's only applicable for C#\VB. var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); if (symbol != null && !symbol.Locations.IsEmpty && symbol.Locations.First().IsInMetadata) { if (!typeOnly || symbol is ITypeSymbol) { var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync(document.Project, symbol, false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; locations.Add(new LSP.Location { Uri = new Uri(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }); } } } return locations.ToArrayAndFree(); // local functions static bool ShouldInclude(INavigableItem item, bool typeOnly) { if (item.Glyph is Glyph.Namespace) { // Never return namespace symbols as part of the go to definition result. return false; } if (!typeOnly) { return true; } switch (item.Glyph) { case Glyph.ClassPublic: case Glyph.ClassProtected: case Glyph.ClassPrivate: case Glyph.ClassInternal: case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: case Glyph.EnumPublic: case Glyph.EnumProtected: case Glyph.EnumPrivate: case Glyph.EnumInternal: case Glyph.EventPublic: case Glyph.EventProtected: case Glyph.EventPrivate: case Glyph.EventInternal: case Glyph.InterfacePublic: case Glyph.InterfaceProtected: case Glyph.InterfacePrivate: case Glyph.InterfaceInternal: case Glyph.ModulePublic: case Glyph.ModuleProtected: case Glyph.ModulePrivate: case Glyph.ModuleInternal: case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return true; default: return false; } } static async Task<IEnumerable<INavigableItem>?> GetDefinitions(Document document, int position, CancellationToken cancellationToken) { // Try IFindDefinitionService first. Until partners implement this, it could fail to find a service, so fall back if it's null. var findDefinitionService = document.GetLanguageService<IFindDefinitionService>(); if (findDefinitionService != null) { return await findDefinitionService.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); } // Removal of this codepath is tracked by https://github.com/dotnet/roslyn/issues/50391. var goToDefinitionsService = document.GetRequiredLanguageService<IGoToDefinitionService>(); return await goToDefinitionsService.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarController_ModelComputation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Threading; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal partial class NavigationBarController { /// <summary> /// Starts a new task to compute the model based on the current text. /// </summary> private async ValueTask<NavigationBarModel> ComputeModelAndSelectItemAsync(ImmutableArray<bool> unused, CancellationToken cancellationToken) { // Jump back to the UI thread to determine what snapshot the user is processing. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textSnapshot = _subjectBuffer.CurrentSnapshot; // Ensure we switch to the threadpool before calling GetDocumentWithFrozenPartialSemantics. It ensures // that any IO that performs is not potentially on the UI thread. await TaskScheduler.Default; var model = await ComputeModelAsync(textSnapshot, cancellationToken).ConfigureAwait(false); // Now, enqueue work to select the right item in this new model. StartSelectedItemUpdateTask(); return model; static async Task<NavigationBarModel> ComputeModelAsync(ITextSnapshot textSnapshot, CancellationToken cancellationToken) { // When computing items just get the partial semantics workspace. This will ensure we can get data for this // file, and hopefully have enough loaded to get data for other files in the case of partial types. In the // event the other files aren't available, then partial-type information won't be correct. That's ok though // as this is just something that happens during solution load and will pass once that is over. By using // partial semantics, we can ensure we don't spend an inordinate amount of time computing and using full // compilation data (like skeleton assemblies). var document = textSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document == null) return null; var itemService = document.GetLanguageService<INavigationBarItemService>(); if (itemService != null) { using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken)) { var items = await itemService.GetItemsAsync(document, textSnapshot.Version, cancellationToken).ConfigureAwait(false); return new NavigationBarModel(itemService, items); } } return new NavigationBarModel(itemService: null, ImmutableArray<NavigationBarItem>.Empty); } } /// <summary> /// Starts a new task to compute what item should be selected. /// </summary> private void StartSelectedItemUpdateTask() { // 'true' value is unused. this just signals to the queue that we have work to do. _selectItemQueue.AddWork(); } private async ValueTask SelectItemAsync(CancellationToken cancellationToken) { // Switch to the UI so we can determine where the user is and determine the state the last time we updated // the UI. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var currentView = _presenter.TryGetCurrentView(); var caretPosition = currentView?.GetCaretPoint(_subjectBuffer); if (!caretPosition.HasValue) return; var position = caretPosition.Value.Position; var lastPresentedInfo = _lastPresentedInfo; // Jump back to the BG to do any expensive work walking the entire model await TaskScheduler.Default; // Ensure the latest model is computed. var model = await _computeModelQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(true); var currentSelectedItem = ComputeSelectedTypeAndMember(model, position, cancellationToken); GetProjectItems(out var projectItems, out var selectedProjectItem); if (Equals(model, lastPresentedInfo.model) && Equals(currentSelectedItem, lastPresentedInfo.selectedInfo) && Equals(selectedProjectItem, lastPresentedInfo.selectedProjectItem) && projectItems.SequenceEqual(lastPresentedInfo.projectItems)) { // Nothing changed, so we can skip presenting these items. return; } // Finally, switch back to the UI to update our state and UI. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _presenter.PresentItems( projectItems, selectedProjectItem, model.Types, currentSelectedItem.TypeItem, currentSelectedItem.MemberItem); _lastPresentedInfo = (projectItems, selectedProjectItem, model, currentSelectedItem); } internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember( NavigationBarModel model, int caretPosition, CancellationToken cancellationToken) { var (item, gray) = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken); if (item == null) { // Nothing to show at all return new NavigationBarSelectedTypeAndMember(null, null); } var rightItem = GetMatchingItem(item.ChildItems, caretPosition, model.ItemService, cancellationToken); return new NavigationBarSelectedTypeAndMember(item, gray, rightItem.item, rightItem.gray); } /// <summary> /// Finds the item that point is in, or if it's not in any items, gets the first item that's /// positioned after the cursor. /// </summary> /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns> private static (NavigationBarItem item, bool gray) GetMatchingItem( ImmutableArray<NavigationBarItem> items, int point, INavigationBarItemService itemsService, CancellationToken cancellationToken) { NavigationBarItem exactItem = null; var exactItemStart = 0; NavigationBarItem nextItem = null; var nextItemStart = int.MaxValue; foreach (var item in items) { foreach (var span in item.Spans) { cancellationToken.ThrowIfCancellationRequested(); if (span.Contains(point) || span.End == point) { // This is the item we should show normally. We'll continue looking at other // items as there might be a nested type that we're actually in. If there // are multiple items containing the point, choose whichever containing span // starts later because that will be the most nested item. if (exactItem == null || span.Start >= exactItemStart) { exactItem = item; exactItemStart = span.Start; } } else if (span.Start > point && span.Start <= nextItemStart) { nextItem = item; nextItemStart = span.Start; } } } if (exactItem != null) { return (exactItem, gray: false); } else { // The second parameter is if we should show it grayed. We'll be nice and say false // unless we actually have an item var itemToGray = nextItem ?? items.LastOrDefault(); if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray)) { itemToGray = null; } return (itemToGray, gray: itemToGray != null); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Threading; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal partial class NavigationBarController { /// <summary> /// Starts a new task to compute the model based on the current text. /// </summary> private async ValueTask<NavigationBarModel> ComputeModelAndSelectItemAsync(ImmutableArray<bool> unused, CancellationToken cancellationToken) { // Jump back to the UI thread to determine what snapshot the user is processing. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var textSnapshot = _subjectBuffer.CurrentSnapshot; // Ensure we switch to the threadpool before calling GetDocumentWithFrozenPartialSemantics. It ensures // that any IO that performs is not potentially on the UI thread. await TaskScheduler.Default; var model = await ComputeModelAsync(textSnapshot, cancellationToken).ConfigureAwait(false); // Now, enqueue work to select the right item in this new model. StartSelectedItemUpdateTask(); return model; static async Task<NavigationBarModel> ComputeModelAsync(ITextSnapshot textSnapshot, CancellationToken cancellationToken) { // When computing items just get the partial semantics workspace. This will ensure we can get data for this // file, and hopefully have enough loaded to get data for other files in the case of partial types. In the // event the other files aren't available, then partial-type information won't be correct. That's ok though // as this is just something that happens during solution load and will pass once that is over. By using // partial semantics, we can ensure we don't spend an inordinate amount of time computing and using full // compilation data (like skeleton assemblies). var document = textSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document == null) return null; var itemService = document.GetLanguageService<INavigationBarItemService>(); if (itemService != null) { using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken)) { var items = await itemService.GetItemsAsync(document, textSnapshot.Version, cancellationToken).ConfigureAwait(false); return new NavigationBarModel(itemService, items); } } return new NavigationBarModel(itemService: null, ImmutableArray<NavigationBarItem>.Empty); } } /// <summary> /// Starts a new task to compute what item should be selected. /// </summary> private void StartSelectedItemUpdateTask() { // 'true' value is unused. this just signals to the queue that we have work to do. _selectItemQueue.AddWork(); } private async ValueTask SelectItemAsync(CancellationToken cancellationToken) { // Switch to the UI so we can determine where the user is and determine the state the last time we updated // the UI. await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var currentView = _presenter.TryGetCurrentView(); var caretPosition = currentView?.GetCaretPoint(_subjectBuffer); if (!caretPosition.HasValue) return; var position = caretPosition.Value.Position; var lastPresentedInfo = _lastPresentedInfo; // Jump back to the BG to do any expensive work walking the entire model await TaskScheduler.Default; // Ensure the latest model is computed. var model = await _computeModelQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(true); var currentSelectedItem = ComputeSelectedTypeAndMember(model, position, cancellationToken); GetProjectItems(out var projectItems, out var selectedProjectItem); if (Equals(model, lastPresentedInfo.model) && Equals(currentSelectedItem, lastPresentedInfo.selectedInfo) && Equals(selectedProjectItem, lastPresentedInfo.selectedProjectItem) && projectItems.SequenceEqual(lastPresentedInfo.projectItems)) { // Nothing changed, so we can skip presenting these items. return; } // Finally, switch back to the UI to update our state and UI. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _presenter.PresentItems( projectItems, selectedProjectItem, model.Types, currentSelectedItem.TypeItem, currentSelectedItem.MemberItem); _lastPresentedInfo = (projectItems, selectedProjectItem, model, currentSelectedItem); } internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember( NavigationBarModel model, int caretPosition, CancellationToken cancellationToken) { var (item, gray) = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken); if (item == null) { // Nothing to show at all return new NavigationBarSelectedTypeAndMember(null, null); } var rightItem = GetMatchingItem(item.ChildItems, caretPosition, model.ItemService, cancellationToken); return new NavigationBarSelectedTypeAndMember(item, gray, rightItem.item, rightItem.gray); } /// <summary> /// Finds the item that point is in, or if it's not in any items, gets the first item that's /// positioned after the cursor. /// </summary> /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns> private static (NavigationBarItem item, bool gray) GetMatchingItem( ImmutableArray<NavigationBarItem> items, int point, INavigationBarItemService itemsService, CancellationToken cancellationToken) { NavigationBarItem exactItem = null; var exactItemStart = 0; NavigationBarItem nextItem = null; var nextItemStart = int.MaxValue; foreach (var item in items) { foreach (var span in item.Spans) { cancellationToken.ThrowIfCancellationRequested(); if (span.Contains(point) || span.End == point) { // This is the item we should show normally. We'll continue looking at other // items as there might be a nested type that we're actually in. If there // are multiple items containing the point, choose whichever containing span // starts later because that will be the most nested item. if (exactItem == null || span.Start >= exactItemStart) { exactItem = item; exactItemStart = span.Start; } } else if (span.Start > point && span.Start <= nextItemStart) { nextItem = item; nextItemStart = span.Start; } } } if (exactItem != null) { return (exactItem, gray: false); } else { // The second parameter is if we should show it grayed. We'll be nice and say false // unless we actually have an item var itemToGray = nextItem ?? items.LastOrDefault(); if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray)) { itemToGray = null; } return (itemToGray, gray: itemToGray != null); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">選択範囲でコード分析を実行(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="new">&amp;Current Document</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="new">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="new">Current Document</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="new">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="new">&amp;Entire Solution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="new">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="new">Entire Solution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="new">&amp;Open Documents</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="new">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="new">Open Documents</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="new">Set Analysis Scope</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="new">Set Analysis Scope</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="new">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">using の並べ替え(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">削除および並べ替え(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">削除および並べ替え(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">アナライザー(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">削除(&amp;R)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">アクティブなルール セットを開く(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">未使用の参照を削除する(&amp;U)...</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">コード分析の実行(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">既定(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">既定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">エラー(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">エラー</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">警告(&amp;W)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">提案事項(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">提案事項</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">サイレント(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">サイレント</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">なし(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">なし</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">ヘルプの表示(&amp;V)...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">アクティブなルール セットとして設定(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">抑制の削除(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">ソース内(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">抑制ファイル内(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">実装に移動</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">実装に移動</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="new">Sync &amp;Namespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="new">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="new">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="new">Track Value Source</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="new">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="new">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">プロジェクトでインタラクティブを初期化</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">プロジェクトから対話的に Visual Basic をリセットする</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">診断</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">診断</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">選択範囲でコード分析を実行(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="new">&amp;Current Document</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="new">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="new">Current Document</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="new">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="new">&amp;Entire Solution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="new">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="new">Entire Solution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="new">&amp;Open Documents</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="new">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="new">Open Documents</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="new">Set Analysis Scope</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="new">Set Analysis Scope</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="new">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">using の並べ替え(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">削除および並べ替え(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">削除および並べ替え(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">アナライザー(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">アナライザーの追加(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">削除(&amp;R)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">アクティブなルール セットを開く(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">未使用の参照を削除する(&amp;U)...</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">コード分析の実行(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">既定(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">既定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">エラー(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">エラー</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">警告(&amp;W)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">提案事項(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">提案事項</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">サイレント(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">サイレント</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">なし(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">なし</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">ヘルプの表示(&amp;V)...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">アクティブなルール セットとして設定(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">抑制の削除(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">ソース内(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">抑制ファイル内(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">実装に移動</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">実装に移動</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="new">Sync &amp;Namespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="new">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="new">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="new">Track Value Source</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="new">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="new">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">プロジェクトでインタラクティブを初期化</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">プロジェクトから対話的に Visual Basic をリセットする</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">診断</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">診断</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">重要度の設定</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">抑制(&amp;U)</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/PullMemberUp/MainDialog/BaseTypeTreeNodeViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog { /// <summary> /// View model used to represent and display the inheritance graph as a tree. This tree is constructed by breadth first searching. /// If one type is the common base type of several other types, it will be showed multiple time. /// </summary> internal class BaseTypeTreeNodeViewModel : SymbolViewModel<INamedTypeSymbol> { /// <summary> /// Base types of this tree node /// </summary> public ImmutableArray<BaseTypeTreeNodeViewModel> BaseTypeNodes { get; private set; } public bool IsExpanded { get; set; } /// <summary> /// Content of the tooltip. /// </summary> public string Namespace => string.Format(ServicesVSResources.Namespace_0, Symbol.ContainingNamespace?.ToDisplayString() ?? "global"); private BaseTypeTreeNodeViewModel(INamedTypeSymbol node, IGlyphService glyphService) : base(node, glyphService) { } /// <summary> /// Use breadth first search to create the inheritance tree. Only non-generated types in the solution will be included in the tree. /// </summary> public static BaseTypeTreeNodeViewModel CreateBaseTypeTree( IGlyphService glyphService, Solution solution, INamedTypeSymbol root, CancellationToken cancellationToken) { var rootTreeNode = new BaseTypeTreeNodeViewModel(root, glyphService) { IsChecked = false, IsExpanded = true }; var queue = new Queue<BaseTypeTreeNodeViewModel>(); queue.Enqueue(rootTreeNode); while (queue.Any()) { var currentTreeNode = queue.Dequeue(); var currentTypeSymbol = currentTreeNode.Symbol; currentTreeNode.BaseTypeNodes = currentTypeSymbol.Interfaces .Concat(currentTypeSymbol.BaseType) .Where(baseType => baseType != null && MemberAndDestinationValidator.IsDestinationValid(solution, baseType, cancellationToken)) .OrderBy(baseType => baseType.ToDisplayString()) .Select(baseType => new BaseTypeTreeNodeViewModel(baseType, glyphService) { IsChecked = false, IsExpanded = true }) .ToImmutableArray(); foreach (var node in currentTreeNode.BaseTypeNodes) { queue.Enqueue(node); } } return rootTreeNode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PullMemberUp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog { /// <summary> /// View model used to represent and display the inheritance graph as a tree. This tree is constructed by breadth first searching. /// If one type is the common base type of several other types, it will be showed multiple time. /// </summary> internal class BaseTypeTreeNodeViewModel : SymbolViewModel<INamedTypeSymbol> { /// <summary> /// Base types of this tree node /// </summary> public ImmutableArray<BaseTypeTreeNodeViewModel> BaseTypeNodes { get; private set; } public bool IsExpanded { get; set; } /// <summary> /// Content of the tooltip. /// </summary> public string Namespace => string.Format(ServicesVSResources.Namespace_0, Symbol.ContainingNamespace?.ToDisplayString() ?? "global"); private BaseTypeTreeNodeViewModel(INamedTypeSymbol node, IGlyphService glyphService) : base(node, glyphService) { } /// <summary> /// Use breadth first search to create the inheritance tree. Only non-generated types in the solution will be included in the tree. /// </summary> public static BaseTypeTreeNodeViewModel CreateBaseTypeTree( IGlyphService glyphService, Solution solution, INamedTypeSymbol root, CancellationToken cancellationToken) { var rootTreeNode = new BaseTypeTreeNodeViewModel(root, glyphService) { IsChecked = false, IsExpanded = true }; var queue = new Queue<BaseTypeTreeNodeViewModel>(); queue.Enqueue(rootTreeNode); while (queue.Any()) { var currentTreeNode = queue.Dequeue(); var currentTypeSymbol = currentTreeNode.Symbol; currentTreeNode.BaseTypeNodes = currentTypeSymbol.Interfaces .Concat(currentTypeSymbol.BaseType) .Where(baseType => baseType != null && MemberAndDestinationValidator.IsDestinationValid(solution, baseType, cancellationToken)) .OrderBy(baseType => baseType.ToDisplayString()) .Select(baseType => new BaseTypeTreeNodeViewModel(baseType, glyphService) { IsChecked = false, IsExpanded = true }) .ToImmutableArray(); foreach (var node in currentTreeNode.BaseTypeNodes) { queue.Enqueue(node); } } return rootTreeNode; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Syntax/UsingDirectiveSyntax.cs
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax { partial class UsingDirectiveSyntax { public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { return Update(globalKeyword: GlobalKeyword, usingKeyword, staticKeyword, alias, name, semicolonToken); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax { partial class UsingDirectiveSyntax { public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { return Update(globalKeyword: GlobalKeyword, usingKeyword, staticKeyword, alias, name, semicolonToken); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/CodeRefactorings/PullMemberUp/CSharpPullMemberUpCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.PullMemberUp), Shared] internal class CSharpPullMemberUpCodeRefactoringProvider : AbstractPullMemberUpRefactoringProvider { /// <summary> /// Test purpose only. /// </summary> [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] public CSharpPullMemberUpCodeRefactoringProvider(IPullMemberUpOptionsService service) : base(service) { } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpPullMemberUpCodeRefactoringProvider() : this(service: null) { } protected override Task<SyntaxNode> GetSelectedNodeAsync(CodeRefactoringContext context) => NodeSelectionHelpers.GetSelectedDeclarationOrVariableAsync(context); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.PullMemberUp), Shared] internal class CSharpPullMemberUpCodeRefactoringProvider : AbstractPullMemberUpRefactoringProvider { /// <summary> /// Test purpose only. /// </summary> [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] public CSharpPullMemberUpCodeRefactoringProvider(IPullMemberUpOptionsService service) : base(service) { } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpPullMemberUpCodeRefactoringProvider() : this(service: null) { } protected override Task<SyntaxNode> GetSelectedNodeAsync(CodeRefactoringContext context) => NodeSelectionHelpers.GetSelectedDeclarationOrVariableAsync(context); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/NavigateTo/RoslynNavigateToItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #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.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #endregion } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.VisualBasic.Testing; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.VisualBasic.Testing; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic()"/> public static DiagnosticResult Diagnostic() => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(string)"/> public static DiagnosticResult Diagnostic(string diagnosticId) => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.Diagnostic(DiagnosticDescriptor)"/> public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(descriptor); /// <summary> /// Verify standard properties of <typeparamref name="TAnalyzer"/>. /// </summary> /// <remarks> /// This validation method is largely specific to dotnet/roslyn scenarios. /// </remarks> public static void VerifyStandardProperty(AnalyzerProperty property) => CodeFixVerifierHelper.VerifyStandardProperty(new TAnalyzer(), property); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyAnalyzerAsync(string, DiagnosticResult[])"/> public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, string)"/> public static async Task VerifyCodeFixAsync(string source, string fixedSource) => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource) => await VerifyCodeFixAsync(source, new[] { expected }, fixedSource); /// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/> public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/AnalyzerDriver/DeclarationInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Struct containing information about a source declaration. /// </summary> internal readonly struct DeclarationInfo { internal DeclarationInfo(SyntaxNode declaredNode, ImmutableArray<SyntaxNode> executableCodeBlocks, ISymbol? declaredSymbol) { Debug.Assert(declaredNode != null); Debug.Assert(!executableCodeBlocks.IsDefault); // TODO: Below assert has been commented out as is not true for VB field decls where multiple variables can share same initializer. // Declared node is the identifier, which doesn't contain the initializer. Can we tweak the assert somehow to handle this case? // Debug.Assert(executableCodeBlocks.All(n => n.Ancestors().Contains(declaredNode))); DeclaredNode = declaredNode; ExecutableCodeBlocks = executableCodeBlocks; DeclaredSymbol = declaredSymbol; } /// <summary> /// Topmost syntax node for this declaration. /// </summary> public SyntaxNode DeclaredNode { get; } /// <summary> /// Syntax nodes for executable code blocks (method body, initializers, etc.) associated with this declaration. /// </summary> public ImmutableArray<SyntaxNode> ExecutableCodeBlocks { get; } /// <summary> /// Symbol declared by this declaration. /// </summary> public ISymbol? DeclaredSymbol { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Struct containing information about a source declaration. /// </summary> internal readonly struct DeclarationInfo { internal DeclarationInfo(SyntaxNode declaredNode, ImmutableArray<SyntaxNode> executableCodeBlocks, ISymbol? declaredSymbol) { Debug.Assert(declaredNode != null); Debug.Assert(!executableCodeBlocks.IsDefault); // TODO: Below assert has been commented out as is not true for VB field decls where multiple variables can share same initializer. // Declared node is the identifier, which doesn't contain the initializer. Can we tweak the assert somehow to handle this case? // Debug.Assert(executableCodeBlocks.All(n => n.Ancestors().Contains(declaredNode))); DeclaredNode = declaredNode; ExecutableCodeBlocks = executableCodeBlocks; DeclaredSymbol = declaredSymbol; } /// <summary> /// Topmost syntax node for this declaration. /// </summary> public SyntaxNode DeclaredNode { get; } /// <summary> /// Syntax nodes for executable code blocks (method body, initializers, etc.) associated with this declaration. /// </summary> public ImmutableArray<SyntaxNode> ExecutableCodeBlocks { get; } /// <summary> /// Symbol declared by this declaration. /// </summary> public ISymbol? DeclaredSymbol { get; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/CodeAnalysisTest/Diagnostics/AnalysisContextInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class AnalysisContextInfoTests { [Fact] public void InitializeTest() { var code = @"class C { void M() { return; } }"; var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None) .WithFeatures(new[] { new KeyValuePair<string, string>("IOperation", "true") }); var compilation = CreateCompilation(code, parseOptions: parseOptions); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSemanticModelAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSymbolAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxNodeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxTreeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterAdditionalFileAction)); } private static void Verify(Compilation compilation, AnalyzerOptions options, string context) { var analyzer = new Analyzer(s => context == s); var diagnostics = compilation.GetAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, options); Assert.Equal(1, diagnostics.Length); Assert.True(diagnostics[0].Descriptor.Description.ToString().IndexOf(analyzer.Info.GetContext()) >= 0); } private class Analyzer : DiagnosticAnalyzer { public const string Id = "exception"; private static readonly DiagnosticDescriptor s_rule = GetRule(Id); private readonly Func<string, bool> _throwPredicate; private AnalysisContextInfo _info; public Analyzer(Func<string, bool> throwPredicate) { _throwPredicate = throwPredicate; } public AnalysisContextInfo Info => _info; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); public override void Initialize(AnalysisContext c) { c.RegisterCodeBlockAction(b => ThrowIfMatch(nameof(c.RegisterCodeBlockAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCodeBlockStartAction<SyntaxKind>(b => ThrowIfMatch(nameof(c.RegisterCodeBlockStartAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCompilationAction(b => ThrowIfMatch(nameof(c.RegisterCompilationAction), new AnalysisContextInfo(b.Compilation))); c.RegisterCompilationStartAction(b => ThrowIfMatch(nameof(c.RegisterCompilationStartAction), new AnalysisContextInfo(b.Compilation))); c.RegisterOperationAction(b => ThrowIfMatch(nameof(c.RegisterOperationAction), new AnalysisContextInfo(b.Compilation, b.Operation)), OperationKind.Return); c.RegisterOperationBlockAction(b => ThrowIfMatch(nameof(c.RegisterOperationBlockAction), new AnalysisContextInfo(b.Compilation, b.OwningSymbol))); c.RegisterSemanticModelAction(b => ThrowIfMatch(nameof(c.RegisterSemanticModelAction), new AnalysisContextInfo(b.SemanticModel))); c.RegisterSymbolAction(b => ThrowIfMatch(nameof(c.RegisterSymbolAction), new AnalysisContextInfo(b.Compilation, b.Symbol)), SymbolKind.NamedType); c.RegisterSyntaxNodeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxNodeAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.Node)), SyntaxKind.ReturnStatement); c.RegisterSyntaxTreeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxTreeAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.Tree)))); c.RegisterAdditionalFileAction(b => ThrowIfMatch(nameof(c.RegisterAdditionalFileAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.AdditionalFile)))); } private void ThrowIfMatch(string context, AnalysisContextInfo info) { if (!_throwPredicate(context)) { return; } _info = info; throw new Exception("exception"); } } private static DiagnosticDescriptor GetRule(string id) { return new DiagnosticDescriptor( id, id, "{0}", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); } private static Compilation CreateCompilation(string source, CSharpParseOptions parseOptions = null) { string fileName = "Test.cs"; string projectName = "TestProject"; var syntaxTree = CSharpSyntaxTree.ParseText(source, path: fileName, options: parseOptions); return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: new[] { TestBase.MscorlibRef }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class AnalysisContextInfoTests { [Fact] public void InitializeTest() { var code = @"class C { void M() { return; } }"; var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None) .WithFeatures(new[] { new KeyValuePair<string, string>("IOperation", "true") }); var compilation = CreateCompilation(code, parseOptions: parseOptions); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSemanticModelAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSymbolAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxNodeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxTreeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterAdditionalFileAction)); } private static void Verify(Compilation compilation, AnalyzerOptions options, string context) { var analyzer = new Analyzer(s => context == s); var diagnostics = compilation.GetAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, options); Assert.Equal(1, diagnostics.Length); Assert.True(diagnostics[0].Descriptor.Description.ToString().IndexOf(analyzer.Info.GetContext()) >= 0); } private class Analyzer : DiagnosticAnalyzer { public const string Id = "exception"; private static readonly DiagnosticDescriptor s_rule = GetRule(Id); private readonly Func<string, bool> _throwPredicate; private AnalysisContextInfo _info; public Analyzer(Func<string, bool> throwPredicate) { _throwPredicate = throwPredicate; } public AnalysisContextInfo Info => _info; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); public override void Initialize(AnalysisContext c) { c.RegisterCodeBlockAction(b => ThrowIfMatch(nameof(c.RegisterCodeBlockAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCodeBlockStartAction<SyntaxKind>(b => ThrowIfMatch(nameof(c.RegisterCodeBlockStartAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCompilationAction(b => ThrowIfMatch(nameof(c.RegisterCompilationAction), new AnalysisContextInfo(b.Compilation))); c.RegisterCompilationStartAction(b => ThrowIfMatch(nameof(c.RegisterCompilationStartAction), new AnalysisContextInfo(b.Compilation))); c.RegisterOperationAction(b => ThrowIfMatch(nameof(c.RegisterOperationAction), new AnalysisContextInfo(b.Compilation, b.Operation)), OperationKind.Return); c.RegisterOperationBlockAction(b => ThrowIfMatch(nameof(c.RegisterOperationBlockAction), new AnalysisContextInfo(b.Compilation, b.OwningSymbol))); c.RegisterSemanticModelAction(b => ThrowIfMatch(nameof(c.RegisterSemanticModelAction), new AnalysisContextInfo(b.SemanticModel))); c.RegisterSymbolAction(b => ThrowIfMatch(nameof(c.RegisterSymbolAction), new AnalysisContextInfo(b.Compilation, b.Symbol)), SymbolKind.NamedType); c.RegisterSyntaxNodeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxNodeAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.Node)), SyntaxKind.ReturnStatement); c.RegisterSyntaxTreeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxTreeAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.Tree)))); c.RegisterAdditionalFileAction(b => ThrowIfMatch(nameof(c.RegisterAdditionalFileAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.AdditionalFile)))); } private void ThrowIfMatch(string context, AnalysisContextInfo info) { if (!_throwPredicate(context)) { return; } _info = info; throw new Exception("exception"); } } private static DiagnosticDescriptor GetRule(string id) { return new DiagnosticDescriptor( id, id, "{0}", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); } private static Compilation CreateCompilation(string source, CSharpParseOptions parseOptions = null) { string fileName = "Test.cs"; string projectName = "TestProject"; var syntaxTree = CSharpSyntaxTree.ParseText(source, path: fileName, options: parseOptions); return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: new[] { TestBase.MscorlibRef }); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Symbols/NonMissingModuleSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="NonMissingModuleSymbol"/> is a special kind of <see cref="ModuleSymbol"/> that represents /// a module that is not missing, i.e. the "real" thing. /// </summary> internal abstract class NonMissingModuleSymbol : ModuleSymbol { /// <summary> /// An array of <see cref="AssemblySymbol"/> objects corresponding to assemblies directly referenced by this module. /// </summary> /// <remarks> /// The contents are provided by ReferenceManager and may not be modified. /// </remarks> private ModuleReferences<AssemblySymbol> _moduleReferences; /// <summary> /// Does this symbol represent a missing module. /// </summary> internal sealed override bool IsMissing { get { return false; } } /// <summary> /// Returns an array of assembly identities for assemblies referenced by this module. /// Items at the same position from GetReferencedAssemblies and from GetReferencedAssemblySymbols /// should correspond to each other. /// </summary> internal sealed override ImmutableArray<AssemblyIdentity> GetReferencedAssemblies() { AssertReferencesInitialized(); return _moduleReferences.Identities; } /// <summary> /// Returns an array of AssemblySymbol objects corresponding to assemblies referenced /// by this module. Items at the same position from GetReferencedAssemblies and /// from GetReferencedAssemblySymbols should correspond to each other. If reference is /// not resolved by compiler, GetReferencedAssemblySymbols returns MissingAssemblySymbol in the /// corresponding item. /// </summary> internal sealed override ImmutableArray<AssemblySymbol> GetReferencedAssemblySymbols() { AssertReferencesInitialized(); return _moduleReferences.Symbols; } internal ImmutableArray<UnifiedAssembly<AssemblySymbol>> GetUnifiedAssemblies() { AssertReferencesInitialized(); return _moduleReferences.UnifiedAssemblies; } internal override bool HasUnifiedReferences { get { return GetUnifiedAssemblies().Length > 0; } } internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType) { AssertReferencesInitialized(); var ownerModule = this; var ownerAssembly = ownerModule.ContainingAssembly; var dependentAssembly = dependentType.ContainingAssembly; if (ownerAssembly == dependentAssembly) { return false; } // TODO (tomat): we should report an error/warning for all unified references, not just the first one. foreach (var unifiedAssembly in GetUnifiedAssemblies()) { if (!ReferenceEquals(unifiedAssembly.TargetAssembly, dependentAssembly)) { continue; } var referenceId = unifiedAssembly.OriginalReference; var definitionId = dependentAssembly.Identity; var involvedAssemblies = ImmutableArray.Create<Symbol>(ownerAssembly, dependentAssembly); DiagnosticInfo info; if (definitionId.Version > referenceId.Version) { // unified with a definition whose version is higher than the reference ErrorCode warning = (definitionId.Version.Major == referenceId.Version.Major && definitionId.Version.Minor == referenceId.Version.Minor) ? ErrorCode.WRN_UnifyReferenceBldRev : ErrorCode.WRN_UnifyReferenceMajMin; // warning: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy. info = new CSDiagnosticInfo( warning, new object[] { referenceId.GetDisplayName(), ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference definitionId.GetDisplayName(), dependentAssembly.Name }, involvedAssemblies, ImmutableArray<Location>.Empty); } else { // unified with a definition whose version is lower than the reference // error: Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}' info = new CSDiagnosticInfo( ErrorCode.ERR_AssemblyMatchBadVersion, new object[] { ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference ownerAssembly.Identity.GetDisplayName(), referenceId.GetDisplayName(), dependentAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference definitionId.GetDisplayName() }, involvedAssemblies, ImmutableArray<Location>.Empty); } if (MergeUseSiteDiagnostics(ref result, info)) { return true; } } return false; } /// <summary> /// A helper method for ReferenceManager to set assembly identities for assemblies /// referenced by this module and corresponding AssemblySymbols. /// </summary> internal override void SetReferences(ModuleReferences<AssemblySymbol> moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null) { Debug.Assert(moduleReferences != null); AssertReferencesUninitialized(); _moduleReferences = moduleReferences; } [Conditional("DEBUG")] internal void AssertReferencesUninitialized() { Debug.Assert(_moduleReferences == null); } [Conditional("DEBUG")] internal void AssertReferencesInitialized() { Debug.Assert(_moduleReferences != null); } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> /// <remarks></remarks> internal sealed override NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName) { NamedTypeSymbol result; NamespaceSymbol scope = this.GlobalNamespace.LookupNestedNamespace(emittedName.NamespaceSegments); if ((object)scope == null) { // We failed to locate the namespace result = new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName); } else { result = scope.LookupMetadataType(ref emittedName); } Debug.Assert((object)result != null); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="NonMissingModuleSymbol"/> is a special kind of <see cref="ModuleSymbol"/> that represents /// a module that is not missing, i.e. the "real" thing. /// </summary> internal abstract class NonMissingModuleSymbol : ModuleSymbol { /// <summary> /// An array of <see cref="AssemblySymbol"/> objects corresponding to assemblies directly referenced by this module. /// </summary> /// <remarks> /// The contents are provided by ReferenceManager and may not be modified. /// </remarks> private ModuleReferences<AssemblySymbol> _moduleReferences; /// <summary> /// Does this symbol represent a missing module. /// </summary> internal sealed override bool IsMissing { get { return false; } } /// <summary> /// Returns an array of assembly identities for assemblies referenced by this module. /// Items at the same position from GetReferencedAssemblies and from GetReferencedAssemblySymbols /// should correspond to each other. /// </summary> internal sealed override ImmutableArray<AssemblyIdentity> GetReferencedAssemblies() { AssertReferencesInitialized(); return _moduleReferences.Identities; } /// <summary> /// Returns an array of AssemblySymbol objects corresponding to assemblies referenced /// by this module. Items at the same position from GetReferencedAssemblies and /// from GetReferencedAssemblySymbols should correspond to each other. If reference is /// not resolved by compiler, GetReferencedAssemblySymbols returns MissingAssemblySymbol in the /// corresponding item. /// </summary> internal sealed override ImmutableArray<AssemblySymbol> GetReferencedAssemblySymbols() { AssertReferencesInitialized(); return _moduleReferences.Symbols; } internal ImmutableArray<UnifiedAssembly<AssemblySymbol>> GetUnifiedAssemblies() { AssertReferencesInitialized(); return _moduleReferences.UnifiedAssemblies; } internal override bool HasUnifiedReferences { get { return GetUnifiedAssemblies().Length > 0; } } internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType) { AssertReferencesInitialized(); var ownerModule = this; var ownerAssembly = ownerModule.ContainingAssembly; var dependentAssembly = dependentType.ContainingAssembly; if (ownerAssembly == dependentAssembly) { return false; } // TODO (tomat): we should report an error/warning for all unified references, not just the first one. foreach (var unifiedAssembly in GetUnifiedAssemblies()) { if (!ReferenceEquals(unifiedAssembly.TargetAssembly, dependentAssembly)) { continue; } var referenceId = unifiedAssembly.OriginalReference; var definitionId = dependentAssembly.Identity; var involvedAssemblies = ImmutableArray.Create<Symbol>(ownerAssembly, dependentAssembly); DiagnosticInfo info; if (definitionId.Version > referenceId.Version) { // unified with a definition whose version is higher than the reference ErrorCode warning = (definitionId.Version.Major == referenceId.Version.Major && definitionId.Version.Minor == referenceId.Version.Minor) ? ErrorCode.WRN_UnifyReferenceBldRev : ErrorCode.WRN_UnifyReferenceMajMin; // warning: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy. info = new CSDiagnosticInfo( warning, new object[] { referenceId.GetDisplayName(), ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference definitionId.GetDisplayName(), dependentAssembly.Name }, involvedAssemblies, ImmutableArray<Location>.Empty); } else { // unified with a definition whose version is lower than the reference // error: Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}' info = new CSDiagnosticInfo( ErrorCode.ERR_AssemblyMatchBadVersion, new object[] { ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference ownerAssembly.Identity.GetDisplayName(), referenceId.GetDisplayName(), dependentAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference definitionId.GetDisplayName() }, involvedAssemblies, ImmutableArray<Location>.Empty); } if (MergeUseSiteDiagnostics(ref result, info)) { return true; } } return false; } /// <summary> /// A helper method for ReferenceManager to set assembly identities for assemblies /// referenced by this module and corresponding AssemblySymbols. /// </summary> internal override void SetReferences(ModuleReferences<AssemblySymbol> moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null) { Debug.Assert(moduleReferences != null); AssertReferencesUninitialized(); _moduleReferences = moduleReferences; } [Conditional("DEBUG")] internal void AssertReferencesUninitialized() { Debug.Assert(_moduleReferences == null); } [Conditional("DEBUG")] internal void AssertReferencesInitialized() { Debug.Assert(_moduleReferences != null); } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> /// <remarks></remarks> internal sealed override NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName) { NamedTypeSymbol result; NamespaceSymbol scope = this.GlobalNamespace.LookupNestedNamespace(emittedName.NamespaceSegments); if ((object)scope == null) { // We failed to locate the namespace result = new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName); } else { result = scope.LookupMetadataType(ref emittedName); } Debug.Assert((object)result != null); return result; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Se creará un espacio de nombres</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Se debe proporcionar un tipo y un nombre.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Acción</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">_Agregar</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Agregar parámetro</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Agregar al archivo _actual</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Se agregó el parámetro.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Se necesitan cambios adicionales para finalizar la refactorización. Revise los cambios a continuación.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos los métodos</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Todos los orígenes</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">Permitir:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Permitir varias líneas en blanco</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Permitir una instrucción inmediatamente después del bloque</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Siempre por claridad</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Analizadores</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Analizando las referencias del proyecto...</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">Aplicar esquema de asignaciones de teclado "{0}"</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Ensamblados</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Evitar instrucciones de expresión que omiten implícitamente el valor</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parámetros sin usar</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Evitar asignaciones de valores sin usar</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Atrás</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Ámbito de análisis en segundo plano:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32 bits</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64 bits</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Compilación y análisis en directo (paquete NuGet)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">Cliente de lenguaje de diagnóstico de C#/Visual Basic</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Calculando dependientes...</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Valor del sitio de llamada:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Sitio de llamada</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">CR + Nueva línea (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">CR (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Categoría</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Elija la acción que quiera realizar en las referencias sin usar.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Estilo de código</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">El análisis de código se ha completado para "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">El análisis de código se ha completado para la solución.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">El análisis de código terminó antes de completarse para "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">El análisis de código terminó antes de completarse para la solución.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Sugerencias de color</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Colorear expresiones regulares</target> <note /> </trans-unit> <trans-unit id="Combine_inheritance_margin_with_indicator_margin"> <source>Combine inheritance margin with indicator margin</source> <target state="new">Combine inheritance margin with indicator margin</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Comentarios</target> <note /> </trans-unit> <trans-unit id="Compute_Quick_Actions_asynchronously_experimental"> <source>Compute Quick Actions asynchronously (experimental, requires restart)</source> <target state="new">Compute Quick Actions asynchronously (experimental, requires restart)</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Miembro contenedor</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Tipo contenedor</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Documento actual</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Parámetro actual</target> <note /> </trans-unit> <trans-unit id="Default_Current_Document"> <source>Default (Current Document)</source> <target state="new">Default (Current Document)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Entire_Solution"> <source>Default (Entire Solution)</source> <target state="new">Default (Entire Solution)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Open_Documents"> <source>Default (Open Documents)</source> <target state="new">Default (Open Documents)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Deshabilitado</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Mostrar todas las sugerencias al presionar Alt+F1</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">_Mostrar sugerencias de nombre de parámetro insertadas</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Mostrar sugerencias de tipo insertado</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Editar</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">Editar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Combinación de colores del editor</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Las opciones de combinación de colores del editor solo están disponibles cuando se usa un tema de color incluido con Visual Studio. Dicho tema se puede configurar desde la página de Entorno &gt; Opciones generales.</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">El elemento no es válido.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Habilitar diagnósticos "pull" de Razor (experimental, requiere reiniciar)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Habilitar todas las características de los archivos abiertos de los generadores de origen (experimental)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Habilitar registro de archivos para el diagnóstico (registrados en la carpeta "%Temp%\Roslyn")</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Habilitar diagnósticos "pull" (experimental, requiere reiniciar)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Habilitado</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Escriba un valor de sitio de llamada o elija otro tipo de inserción de valor.</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Todo el repositorio</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Toda la solución</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Error</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Actualización de errores de forma periódica: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Evaluando ({0} tareas en cola)</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Extraer clase base</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Finalizar</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Dar formato al documento</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Generar archivo .editorconfig a partir de la configuración</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">Resaltar componentes relacionados bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">Id.</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Miembros implementados</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Implementando miembros</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">En otros operadores</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Índice</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Inferir del contexto</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Indexado en la organización</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Indexado en el repositorio</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin"> <source>Inheritance Margin</source> <target state="new">Inheritance Margin</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="new">Inline Hints</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Insertando el valor del sitio de llamada "{0}"</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Instale los analizadores de Roslyn recomendados por Microsoft, que proporcionan diagnósticos y correcciones adicionales para problemas comunes de confiabilidad, rendimiento, seguridad y diseño de API.</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">La interfaz no puede tener campos.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Introducir variables TODO sin definir</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Origen del elemento</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Mantener</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Mantener todos los paréntesis en:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Tipo</target> <note /> </trans-unit> <trans-unit id="Language_client_initialization_failed"> <source>{0} failed to initialize. Status = {1}. Exception = {2}</source> <target state="new">{0} failed to initialize. Status = {1}. Exception = {2}</target> <note>{0} is the language server name. Status is the status of the initialization. Exception is the exception encountered during initialization.</note> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Análisis en directo (extensión VSIX)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Elementos cargados</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Solución cargada</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Local</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Metadatos locales</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">Convertir "{0}" en abstracto</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Convertir en abstracto</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Miembros</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Preferencias de modificador:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Mover a espacio de nombres</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Varios miembros son heredados</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">Varios miembros se heredan en la línea {0}</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">El nombre está en conflicto con un nombre de tipo que ya existía.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">El nombre no es un identificador de {0} válido.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Espacio de nombres</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Espacio de nombres: "{0}"</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="Namespaces_have_been_updated"> <source>Namespaces have been updated.</source> <target state="new">Namespaces have been updated.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">campo</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">Local</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">función local</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">método</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">parámetro</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">propiedad</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">parámetro de tipo</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Campo</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Local</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">método</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Parámetro</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Parámetro de tipo</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Reglas de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">Navegar a "{0}"</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca si es innecesario</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Nombre de tipo nuevo:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Nuevas preferencias de línea (experimental):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Nueva línea (\\n)</target> <note /> </trans-unit> <trans-unit id="No_namespaces_needed_updating"> <source>No namespaces needed updating.</source> <target state="new">No namespaces needed updating.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">No se encontraron referencias sin usar.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Miembros no públicos</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Omitir (solo para parámetros opcionales)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Documentos abiertos</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">Los parámetros opcionales deben proporcionar un valor predeterminado.</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Opcional con valor predeterminado:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Otros</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Miembros reemplazados</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Reemplando miembros</target> <note /> </trans-unit> <trans-unit id="Package_install_canceled"> <source>Package install canceled</source> <target state="new">Package install canceled</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_canceled"> <source>Package uninstall canceled</source> <target state="new">Package uninstall canceled</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Paquetes</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Detalles de parámetros</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Nombre del parámetro:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Información de parámetros</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Clase de parámetro</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">El nombre de parámetro contiene caracteres no válidos.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Preferencias de parámetros:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">El tipo de parámetro contiene caracteres no válidos.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Preferencias de paréntesis:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">En pausa ({0} tareas en cola)</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Escriba un nombre de tipo.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Preferir "System.HashCode" en "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir asignaciones compuestas</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Preferir operador de índice</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Preferir operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos de solo lectura</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Preferir la instrucción "using" sencilla</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expresiones booleanas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Preferir funciones locales estáticas</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Proyectos</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Extraer miembros</target> <note /> </trans-unit> <trans-unit id="Quick_Actions"> <source>Quick Actions</source> <target state="new">Quick Actions</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Solo refactorización</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Referencia</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Expresiones regulares</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Quitar todo</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Quitar referencias sin usar</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">Cambiar nombre de {0} a {1}</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Notificar expresiones regulares no válidas</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Repositorio</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Requerir:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Obligatorio</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Requiere que "System.HashCode" esté presente en el proyecto</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Restablecer asignaciones de teclado predeterminadas de Visual Studio</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Revisar cambios</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">Ejecutar análisis de código en {0}</target> <note /> </trans-unit> <trans-unit id="Run_code_analysis_in_separate_process_requires_restart"> <source>Run code analysis in separate process (requires restart)</source> <target state="new">Run code analysis in separate process (requires restart)</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">Ejecutando el análisis de código para "{0}"...</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Ejecutando el análisis de código para la solución...</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Ejecutando procesos en segundo plano de baja prioridad</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">Guardar archivo .editorconfig</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Buscar configuración</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Seleccionar destino</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">Seleccionar _dependientes</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">Seleccionar _público</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Seleccionar destino y miembros para extraer.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Seleccionar destino:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Seleccionar miembro</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Seleccionar miembros:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Mostrar el comando "Quitar referencias sin usar" en el Explorador de soluciones (experimental)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Mostrar lista de finalización</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Mostrar sugerencias para todo lo demás</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Mostrar sugerencias para la creación implícita de objetos</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_indexers"> <source>Show hints for indexers</source> <target state="new">Show hints for indexers</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Mostrar sugerencias para los tipos de parámetros lambda</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Mostrar sugerencias para los literales</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Mostrar sugerencias para las variables con tipos inferidos</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Mostrar margen de herencia</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Algunos de los colores de la combinación se reemplazan por los cambios realizados en la página de opciones de Entorno &gt; Fuentes y colores. Elija "Usar valores predeterminados" en la página Fuentes y colores para revertir todas las personalizaciones.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Sugerencia</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Suprimir las sugerencias cuando el nombre del parámetro coincida con la intención del método</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Suprimir las sugerencias cuando los nombres de parámetro solo se diferencien por el sufijo</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Símbolos sin referencias</target> <note /> </trans-unit> <trans-unit id="Sync_Namespaces"> <source>Sync Namespaces</source> <target state="new">Sync Namespaces</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Presionar dos veces la tecla Tab para insertar argumentos (experimental)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Espacio de nombres de destino:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">El generador "{0}" que creó este archivo se ha quitado del proyecto; el archivo ya no se incluye en el proyecto.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">El generador "{0}" que creaba este archivo ha dejado de generarlo; el archivo ya no se incluye en el proyecto.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Esta acción no se puede deshacer. ¿Quiere continuar?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">El generador "{0}" crea este archivo de forma automática y no se puede editar.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Este espacio de nombres no es válido</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Título</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Nombre de tipo:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">El nombre de tipo tiene un error de sintaxis</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">No se reconoce el nombre de tipo</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Se reconoce el nombre de tipo</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">El valor sin usar se asigna explícitamente a una variable local sin usar</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">El valor sin usar se asigna explícitamente para descartar</target> <note /> </trans-unit> <trans-unit id="Updating_namspaces"> <source>Updating namespaces...</source> <target state="new">Updating namespaces...</target> <note>"namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Actualizando las referencias del proyecto...</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Actualizando la gravedad</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Usar cuerpo de expresión para lambdas</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar cuerpo de expresión para funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Usar argumento con nombre</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Valor</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">El valor asignado aquí no se usa nunca</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Valor:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">El valor devuelto por la invocación se omite implícitamente</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Valor que se va a insertar en los sitios de llamada</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Advertencia</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Advertencia: Nombre de parámetro duplicado</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Advertencia: El tipo no se enlaza</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">Observamos que ha suspendido "{0}". Restablezca las asignaciones de teclado para continuar navegando y refactorizando.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Esta área de trabajo no admite la actualización de opciones de compilación de Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">Debe cambiar la firma</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">Debe seleccionar al menos un miembro.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Caracteres no válidos en la ruta de acceso.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">El nombre de archivo debe tener la extensión "{0}".</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Depurador</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Determinando la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">Determinando automático...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Resolviendo la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Validando la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">Obteniendo texto de sugerencia de datos...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Vista previa no disponible</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Invalidaciones</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Invalidado por</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Hereda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Heredado por</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementa</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Está abierto el número máximo de documentos.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">No se pudo crear el documento en el proyecto de archivos varios.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Acceso no válido.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">No se encontraron las siguientes referencias. {0}Búsquelas y agréguelas manualmente.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">La posición final debe ser &gt;= que la posición de inicio</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">No es un valor válido</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">"{0}" is heredado</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">"{0}" se cambiará a abstracto.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">"{0}" se cambiará a no estático.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">"{0}" se cambiará a público.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[generado por {0}]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[generado]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">el área de trabajo determinada no permite deshacer</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">Agregar una referencia a "{0}"</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">El tipo de evento no es válido</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">No se puede encontrar un lugar para insertar el miembro</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">No se puede cambiar el nombre de los elementos "otro"</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Tipo de cambio de nombre desconocido</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Los identificadores no son compatibles con este tipo de símbolo.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">No se puede crear un identificador de nodo para el tipo de símbolo: "{0}"</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Referencias del proyecto</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Tipos base</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Archivos varios</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">No se pudo encontrar el proyecto "{0}"</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">No se pudo encontrar la ubicación de la carpeta en el disco</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Ensamblado </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Excepciones:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">Miembro de {0}</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Parámetros:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Proyecto </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Comentarios:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Devuelve:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Resumen:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Parámetros de tipo:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Ya existe el archivo</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">La ruta de acceso del archivo no puede usar palabras clave reservadas</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">El valor de DocumentPath no es válido</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">La ruta de acceso del proyecto no es válida</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">La ruta de acceso no puede tener un nombre de archivo vacío</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">El DocumentId en cuestión no provenía del área de trabajo de Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proyecto: {0} ({1}) Use la lista desplegable para ver y cambiar a otros proyectos a los que puede pertenecer este archivo.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Use el menú desplegable para ver y navegar a otros elementos de este archivo.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proyecto: {0} Use la lista desplegable para ver y cambiar a otros proyectos a los que puede pertenecer este archivo.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">El ensamblado del analizador "{0}" cambió. Los diagnósticos podrían ser incorrectos hasta que se reinicie Visual Studio.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">Origen de datos de tabla de diagnóstico de C#/VB</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">Origen de datos de tabla de lista de tareas pendientes de C#/VB</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Anular toda la selección</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Extraer interfaz</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Nombre generado:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Nuevo nombre de _archivo:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">_Nuevo nombre de interfaz:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">Aceptar</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">_Seleccionar todo</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Seleccionar miembros _públicos para formar interfaz</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">_Acceso:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">Agregar a archivo _existente</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Cambiar firma</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">_Crear nuevo archivo</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">Predeterminado</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Nombre de archivo:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Generar tipo</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Tipo:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Ubicación:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Modificador</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Nombre:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Parámetro</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Parámetros:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Vista previa de signatura de método:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Vista previa de cambios de referencia</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Proyecto:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Tipo</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Detalles del tipo:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">Qui_tar</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Restablecer</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">Más información sobre {0}</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">La navegación se debe realizar en el subproceso en primer plano.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">Referencia a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Desconocido&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">Referencia del analizador a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">Referencia del proyecto a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">Los dos ensamblados del analizador, "{0}" y "{1}", tienen la identidad "{2}" pero contenido distinto. Solo se cargará uno de ellos y es posible que estos analizadores no se ejecuten correctamente.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} referencias</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 referencia</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">"{0}" detectó un error y se ha deshabilitado.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Habilitar</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Habilitar y omitir futuros errores</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Sin cambios</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Bloque actual</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Determinando el bloque actual.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">Origen de datos de tabla de compilación de C#/VB</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">El ensamblado del analizador "{0}" depende de "{1}", pero no se encontró. Es posible que los analizadores no se ejecuten correctamente, a menos que el ensamblado que falta se agregue también como referencia del analizador.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Suprimir diagnóstico</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Procesando corrección de supresiones...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Aplicando corrección de supresiones...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Quitar supresiones</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Procesando corrección para quitar supresiones...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Aplicando corrección para quitar supresiones...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">El área de trabajo solo permite abrir documentos en el subproceso de interfaz de usuario.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Esta área de trabajo no admite la actualización de opciones de análisis de Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">Sincronizar {0}</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">Sincronizando con {0}...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio suspendió algunas características avanzadas para mejorar el rendimiento.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">Instalando "{0}"</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">Instalación de "{0}" completada</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">No se pudo instalar el paquete: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Desconocido&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">No</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sí</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Elija una especificación de símbolo y un estilo de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Escriba un título para la regla de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Escriba un título para el estilo de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Escriba un título para la especificación de símbolo.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Accesibilidades (puede coincidir con cualquiera)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Uso de mayúsculas:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">todo en minúsculas</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">TODO EN MAYÚSCULAS</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">Nombre en camel Case</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">Primera palabra en mayúsculas</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Nombre en Pascal Case</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Gravedad</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Modificadores (deben coincidir todos)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Nombre:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Estilo de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Estilo de nomenclatura:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Las reglas de nomenclatura le permiten definir qué nombres se deben establecer para los conjuntos especiales de símbolos y cómo se debe tratar con los símbolos con nombres incorrectos.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">La primera regla de nomenclatura coincidente de nivel superior se usa de manera predeterminada cuando se asigna un nombre a un símbolo, mientras que todo caso especial se administra según una regla secundaria coincidente.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Título de estilo de nomenclatura:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Regla principal:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Prefijo requerido:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Sufijo requerido:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Identificador de ejemplo:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Tipos de símbolo (pueden coincidir con cualquiera)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Especificación de símbolo:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Título de especificación de símbolo:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Separador de palabras:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">ejemplo</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">identificador</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">Instalar "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">Desinstalando "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">Deinstalación de "{0}" completada</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">Desinstalar "{0}"</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">No se pudo desinstalar el paquete: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Se encontró un error al cargar el proyecto. Se deshabilitaron algunas características del proyecto, como el análisis completo de la solución del proyecto con error y los proyectos que dependen de él.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">No se pudo cargar el proyecto.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Para descubrir la causa del problema, pruebe lo siguiente. 1. Cierre Visual Studio 2. Abra un símbolo del sistema para desarrolladores de Visual Studio. 3. Establezca la variable de entorno “TraceDesignTime” en true (TraceDesignTime=true). 4. Elimine el archivo .suo en el directorio .vs. 5. Reinicie VS desde el símbolo del sistema donde estableció la variable de entorno (devenv). 6. Abra la solución. 7. Compruebe “{0}”y busque las tareas con errores (FAILED).</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Información adicional:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">No se pudo instalar "{0}". Información adicional: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">No se pudo desinstalar "{0}". Información adicional: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">Mover {0} bajo {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">Mover {0} sobre {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">Quitar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">Restaurar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Volver a habilitar</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Más información</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de marco de trabajo</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Copiar al Portapapeles</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Cerrar</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Parámetros desconocidos&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- Fin del seguimiento de la pila de la excepción interna ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para variables locales, parámetros y miembros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expresiones de acceso a miembro</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">Preferencias de expresión:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Guías de estructura de bloque</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Esquematización</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Mostrar guías para construcciones a nivel de código</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Mostrar guías para regiones de preprocesador y comentarios</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Mostrar guías para construcciones a nivel de declaración</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Mostrar esquematización para construcciones a nivel de código</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Mostrar esquematización para regiones de preprocesador y comentarios</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Mostrar esquematización para construcciones a nivel de declaración</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Preferencias de variable:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Preferir declaración de variable insertada</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar cuerpo de expresiones para los métodos</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Preferencias de bloque de código:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar cuerpo de expresiones para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar cuerpo de expresiones para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar cuerpo de expresiones para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar cuerpo de expresiones para las propiedades</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Algunas reglas de nomenclatura están incompletas. Complételas o quítelas.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Administrar especificaciones</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Reordenar</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Gravedad</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Especificación</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Estilo requerido</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">No se puede eliminar este elemento porque una regla de nomenclatura existente lo usa.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir inicializador de colección</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir expresión de fusión</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Contraer #regions cuando se contraiga a las definiciones</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir propagación nula</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nombre de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Descripción</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Preferencia</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Implementar interfaz o clase abstracta</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Para un símbolo determinado, solo se aplicará la regla superior con una "especificación" concordante. Si se infringe el "estilo requerido" de esa regla, se informará en el nivel de "gravedad" elegido.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">al final</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">Al insertar propiedades, eventos y métodos, colóquelos:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">Con otros miembros de la misma clase</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Preferir llaves</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">Antes que:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Preferir:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">o</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">Tipos integrados</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">En cualquier otra parte</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">El tipo es aparente en la expresión de asignación</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Bajar</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Subir</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Quitar</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Seleccionar miembros</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">Lamentablemente, un proceso utilizado por Visual Studio ha encontrado un error irrecuperable. Recomendamos que guarde su trabajo y luego cierre y reinicie Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Agregar una especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Quitar especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Agregar elemento</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Editar elemento</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Quitar elemento</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Agregar una regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Quitar regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">No se puede llamar a VisualStudioWorkspace.TryApplyChanges desde un subproceso en segundo plano.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">preferir propiedades de lanzamiento</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">Al generar propiedades:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Opciones</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">No volver a mostrar</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Preferir la expresión simple "predeterminada"</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir nombres de elementos de tupla inferidos</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Preferir nombres de miembro de tipo anónimo inferidos</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Panel de vista previa</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Análisis</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Atenuar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Atenuando</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Preferir una función local frente a una función anónima</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Preferir declaración de variable desconstruida</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Se encontró una referencia externa</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">No se encontraron referencias a "{0}"</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">No se encontraron resultados para la búsqueda</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propiedades automáticas</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">preferir propiedades automáticas</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">El módulo se descargó.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Habilitar la navegación a orígenes decompilados (experimental)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">El archivo .editorconfig puede invalidar la configuración local definida en esta página que solo se aplica a su máquina. Para configurar estos valores de manera que se desplacen con su solución, use los archivos EditorConfig. Mas información</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Sincronizar vista de clases</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">Analizando “{0}”</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Administrar estilos de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expresión condicional sobre "if" con asignaciones</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expresión condicional sobre "if" con devoluciones</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Se creará un espacio de nombres</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Se debe proporcionar un tipo y un nombre.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Acción</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">_Agregar</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Agregar parámetro</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Agregar al archivo _actual</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Se agregó el parámetro.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Se necesitan cambios adicionales para finalizar la refactorización. Revise los cambios a continuación.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos los métodos</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Todos los orígenes</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">Permitir:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Permitir varias líneas en blanco</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Permitir una instrucción inmediatamente después del bloque</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Siempre por claridad</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Analizadores</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Analizando las referencias del proyecto...</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">Aplicar esquema de asignaciones de teclado "{0}"</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Ensamblados</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Evitar instrucciones de expresión que omiten implícitamente el valor</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parámetros sin usar</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Evitar asignaciones de valores sin usar</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Atrás</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Ámbito de análisis en segundo plano:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32 bits</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64 bits</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Compilación y análisis en directo (paquete NuGet)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">Cliente de lenguaje de diagnóstico de C#/Visual Basic</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Calculando dependientes...</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Valor del sitio de llamada:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Sitio de llamada</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">CR + Nueva línea (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">CR (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Categoría</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Elija la acción que quiera realizar en las referencias sin usar.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Estilo de código</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">El análisis de código se ha completado para "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">El análisis de código se ha completado para la solución.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">El análisis de código terminó antes de completarse para "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">El análisis de código terminó antes de completarse para la solución.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Sugerencias de color</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Colorear expresiones regulares</target> <note /> </trans-unit> <trans-unit id="Combine_inheritance_margin_with_indicator_margin"> <source>Combine inheritance margin with indicator margin</source> <target state="new">Combine inheritance margin with indicator margin</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Comentarios</target> <note /> </trans-unit> <trans-unit id="Compute_Quick_Actions_asynchronously_experimental"> <source>Compute Quick Actions asynchronously (experimental, requires restart)</source> <target state="new">Compute Quick Actions asynchronously (experimental, requires restart)</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Miembro contenedor</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Tipo contenedor</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Documento actual</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Parámetro actual</target> <note /> </trans-unit> <trans-unit id="Default_Current_Document"> <source>Default (Current Document)</source> <target state="new">Default (Current Document)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Entire_Solution"> <source>Default (Entire Solution)</source> <target state="new">Default (Entire Solution)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Open_Documents"> <source>Default (Open Documents)</source> <target state="new">Default (Open Documents)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Deshabilitado</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Mostrar todas las sugerencias al presionar Alt+F1</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">_Mostrar sugerencias de nombre de parámetro insertadas</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Mostrar sugerencias de tipo insertado</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Editar</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">Editar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Combinación de colores del editor</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Las opciones de combinación de colores del editor solo están disponibles cuando se usa un tema de color incluido con Visual Studio. Dicho tema se puede configurar desde la página de Entorno &gt; Opciones generales.</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">El elemento no es válido.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Habilitar diagnósticos "pull" de Razor (experimental, requiere reiniciar)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Habilitar todas las características de los archivos abiertos de los generadores de origen (experimental)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Habilitar registro de archivos para el diagnóstico (registrados en la carpeta "%Temp%\Roslyn")</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Habilitar diagnósticos "pull" (experimental, requiere reiniciar)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Habilitado</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Escriba un valor de sitio de llamada o elija otro tipo de inserción de valor.</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Todo el repositorio</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Toda la solución</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Error</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Actualización de errores de forma periódica: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Evaluando ({0} tareas en cola)</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Extraer clase base</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Finalizar</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Dar formato al documento</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Generar archivo .editorconfig a partir de la configuración</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">Resaltar componentes relacionados bajo el cursor</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">Id.</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Miembros implementados</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Implementando miembros</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">En otros operadores</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Índice</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Inferir del contexto</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Indexado en la organización</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Indexado en el repositorio</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin"> <source>Inheritance Margin</source> <target state="new">Inheritance Margin</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="new">Inline Hints</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Insertando el valor del sitio de llamada "{0}"</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Instale los analizadores de Roslyn recomendados por Microsoft, que proporcionan diagnósticos y correcciones adicionales para problemas comunes de confiabilidad, rendimiento, seguridad y diseño de API.</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">La interfaz no puede tener campos.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Introducir variables TODO sin definir</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Origen del elemento</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Mantener</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Mantener todos los paréntesis en:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Tipo</target> <note /> </trans-unit> <trans-unit id="Language_client_initialization_failed"> <source>{0} failed to initialize. Status = {1}. Exception = {2}</source> <target state="new">{0} failed to initialize. Status = {1}. Exception = {2}</target> <note>{0} is the language server name. Status is the status of the initialization. Exception is the exception encountered during initialization.</note> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Análisis en directo (extensión VSIX)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Elementos cargados</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Solución cargada</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Local</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Metadatos locales</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">Convertir "{0}" en abstracto</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Convertir en abstracto</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Miembros</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Preferencias de modificador:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Mover a espacio de nombres</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Varios miembros son heredados</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">Varios miembros se heredan en la línea {0}</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">El nombre está en conflicto con un nombre de tipo que ya existía.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">El nombre no es un identificador de {0} válido.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Espacio de nombres</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Espacio de nombres: "{0}"</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="Namespaces_have_been_updated"> <source>Namespaces have been updated.</source> <target state="new">Namespaces have been updated.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">campo</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">Local</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">función local</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">método</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">parámetro</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">propiedad</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">parámetro de tipo</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Campo</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Local</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">método</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Parámetro</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Parámetro de tipo</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Reglas de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">Navegar a "{0}"</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca si es innecesario</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Nombre de tipo nuevo:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Nuevas preferencias de línea (experimental):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Nueva línea (\\n)</target> <note /> </trans-unit> <trans-unit id="No_namespaces_needed_updating"> <source>No namespaces needed updating.</source> <target state="new">No namespaces needed updating.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">No se encontraron referencias sin usar.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Miembros no públicos</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Omitir (solo para parámetros opcionales)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Documentos abiertos</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">Los parámetros opcionales deben proporcionar un valor predeterminado.</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Opcional con valor predeterminado:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Otros</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Miembros reemplazados</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Reemplando miembros</target> <note /> </trans-unit> <trans-unit id="Package_install_canceled"> <source>Package install canceled</source> <target state="new">Package install canceled</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_canceled"> <source>Package uninstall canceled</source> <target state="new">Package uninstall canceled</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Paquetes</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Detalles de parámetros</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Nombre del parámetro:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Información de parámetros</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Clase de parámetro</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">El nombre de parámetro contiene caracteres no válidos.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Preferencias de parámetros:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">El tipo de parámetro contiene caracteres no válidos.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Preferencias de paréntesis:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">En pausa ({0} tareas en cola)</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Escriba un nombre de tipo.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Preferir "System.HashCode" en "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir asignaciones compuestas</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Preferir operador de índice</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Preferir operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos de solo lectura</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Preferir la instrucción "using" sencilla</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expresiones booleanas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Preferir funciones locales estáticas</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Proyectos</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Extraer miembros</target> <note /> </trans-unit> <trans-unit id="Quick_Actions"> <source>Quick Actions</source> <target state="new">Quick Actions</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Solo refactorización</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Referencia</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Expresiones regulares</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Quitar todo</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Quitar referencias sin usar</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">Cambiar nombre de {0} a {1}</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Notificar expresiones regulares no válidas</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Repositorio</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Requerir:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Obligatorio</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Requiere que "System.HashCode" esté presente en el proyecto</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Restablecer asignaciones de teclado predeterminadas de Visual Studio</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Revisar cambios</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">Ejecutar análisis de código en {0}</target> <note /> </trans-unit> <trans-unit id="Run_code_analysis_in_separate_process_requires_restart"> <source>Run code analysis in separate process (requires restart)</source> <target state="new">Run code analysis in separate process (requires restart)</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">Ejecutando el análisis de código para "{0}"...</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Ejecutando el análisis de código para la solución...</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Ejecutando procesos en segundo plano de baja prioridad</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">Guardar archivo .editorconfig</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Buscar configuración</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Seleccionar destino</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">Seleccionar _dependientes</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">Seleccionar _público</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Seleccionar destino y miembros para extraer.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Seleccionar destino:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Seleccionar miembro</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Seleccionar miembros:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Mostrar el comando "Quitar referencias sin usar" en el Explorador de soluciones (experimental)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Mostrar lista de finalización</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Mostrar sugerencias para todo lo demás</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Mostrar sugerencias para la creación implícita de objetos</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_indexers"> <source>Show hints for indexers</source> <target state="new">Show hints for indexers</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Mostrar sugerencias para los tipos de parámetros lambda</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Mostrar sugerencias para los literales</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Mostrar sugerencias para las variables con tipos inferidos</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Mostrar margen de herencia</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Algunos de los colores de la combinación se reemplazan por los cambios realizados en la página de opciones de Entorno &gt; Fuentes y colores. Elija "Usar valores predeterminados" en la página Fuentes y colores para revertir todas las personalizaciones.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Sugerencia</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Suprimir las sugerencias cuando el nombre del parámetro coincida con la intención del método</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Suprimir las sugerencias cuando los nombres de parámetro solo se diferencien por el sufijo</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Símbolos sin referencias</target> <note /> </trans-unit> <trans-unit id="Sync_Namespaces"> <source>Sync Namespaces</source> <target state="new">Sync Namespaces</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Presionar dos veces la tecla Tab para insertar argumentos (experimental)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Espacio de nombres de destino:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">El generador "{0}" que creó este archivo se ha quitado del proyecto; el archivo ya no se incluye en el proyecto.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">El generador "{0}" que creaba este archivo ha dejado de generarlo; el archivo ya no se incluye en el proyecto.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Esta acción no se puede deshacer. ¿Quiere continuar?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">El generador "{0}" crea este archivo de forma automática y no se puede editar.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Este espacio de nombres no es válido</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Título</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Nombre de tipo:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">El nombre de tipo tiene un error de sintaxis</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">No se reconoce el nombre de tipo</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Se reconoce el nombre de tipo</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">El valor sin usar se asigna explícitamente a una variable local sin usar</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">El valor sin usar se asigna explícitamente para descartar</target> <note /> </trans-unit> <trans-unit id="Updating_namspaces"> <source>Updating namespaces...</source> <target state="new">Updating namespaces...</target> <note>"namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Actualizando las referencias del proyecto...</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Actualizando la gravedad</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Usar cuerpo de expresión para lambdas</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar cuerpo de expresión para funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Usar argumento con nombre</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Valor</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">El valor asignado aquí no se usa nunca</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Valor:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">El valor devuelto por la invocación se omite implícitamente</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Valor que se va a insertar en los sitios de llamada</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Advertencia</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Advertencia: Nombre de parámetro duplicado</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Advertencia: El tipo no se enlaza</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">Observamos que ha suspendido "{0}". Restablezca las asignaciones de teclado para continuar navegando y refactorizando.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Esta área de trabajo no admite la actualización de opciones de compilación de Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">Debe cambiar la firma</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">Debe seleccionar al menos un miembro.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Caracteres no válidos en la ruta de acceso.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">El nombre de archivo debe tener la extensión "{0}".</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Depurador</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Determinando la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">Determinando automático...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Resolviendo la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Validando la ubicación del punto de interrupción...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">Obteniendo texto de sugerencia de datos...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Vista previa no disponible</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Invalidaciones</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Invalidado por</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Hereda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Heredado por</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementa</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Está abierto el número máximo de documentos.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">No se pudo crear el documento en el proyecto de archivos varios.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Acceso no válido.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">No se encontraron las siguientes referencias. {0}Búsquelas y agréguelas manualmente.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">La posición final debe ser &gt;= que la posición de inicio</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">No es un valor válido</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">"{0}" is heredado</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">"{0}" se cambiará a abstracto.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">"{0}" se cambiará a no estático.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">"{0}" se cambiará a público.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[generado por {0}]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[generado]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">el área de trabajo determinada no permite deshacer</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">Agregar una referencia a "{0}"</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">El tipo de evento no es válido</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">No se puede encontrar un lugar para insertar el miembro</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">No se puede cambiar el nombre de los elementos "otro"</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Tipo de cambio de nombre desconocido</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Los identificadores no son compatibles con este tipo de símbolo.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">No se puede crear un identificador de nodo para el tipo de símbolo: "{0}"</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Referencias del proyecto</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Tipos base</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Archivos varios</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">No se pudo encontrar el proyecto "{0}"</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">No se pudo encontrar la ubicación de la carpeta en el disco</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Ensamblado </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Excepciones:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">Miembro de {0}</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Parámetros:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Proyecto </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Comentarios:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Devuelve:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Resumen:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Parámetros de tipo:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Ya existe el archivo</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">La ruta de acceso del archivo no puede usar palabras clave reservadas</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">El valor de DocumentPath no es válido</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">La ruta de acceso del proyecto no es válida</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">La ruta de acceso no puede tener un nombre de archivo vacío</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">El DocumentId en cuestión no provenía del área de trabajo de Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proyecto: {0} ({1}) Use la lista desplegable para ver y cambiar a otros proyectos a los que puede pertenecer este archivo.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Use el menú desplegable para ver y navegar a otros elementos de este archivo.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proyecto: {0} Use la lista desplegable para ver y cambiar a otros proyectos a los que puede pertenecer este archivo.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">El ensamblado del analizador "{0}" cambió. Los diagnósticos podrían ser incorrectos hasta que se reinicie Visual Studio.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">Origen de datos de tabla de diagnóstico de C#/VB</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">Origen de datos de tabla de lista de tareas pendientes de C#/VB</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Anular toda la selección</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Extraer interfaz</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Nombre generado:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Nuevo nombre de _archivo:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">_Nuevo nombre de interfaz:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">Aceptar</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">_Seleccionar todo</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Seleccionar miembros _públicos para formar interfaz</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">_Acceso:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">Agregar a archivo _existente</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Cambiar firma</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">_Crear nuevo archivo</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">Predeterminado</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Nombre de archivo:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Generar tipo</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Tipo:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Ubicación:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Modificador</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Nombre:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Parámetro</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Parámetros:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Vista previa de signatura de método:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Vista previa de cambios de referencia</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Proyecto:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Tipo</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Detalles del tipo:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">Qui_tar</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Restablecer</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">Más información sobre {0}</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">La navegación se debe realizar en el subproceso en primer plano.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">Referencia a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Desconocido&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">Referencia del analizador a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">Referencia del proyecto a "{0}" en el proyecto "{1}"</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">Los dos ensamblados del analizador, "{0}" y "{1}", tienen la identidad "{2}" pero contenido distinto. Solo se cargará uno de ellos y es posible que estos analizadores no se ejecuten correctamente.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} referencias</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 referencia</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">"{0}" detectó un error y se ha deshabilitado.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Habilitar</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Habilitar y omitir futuros errores</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Sin cambios</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Bloque actual</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Determinando el bloque actual.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">Origen de datos de tabla de compilación de C#/VB</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">El ensamblado del analizador "{0}" depende de "{1}", pero no se encontró. Es posible que los analizadores no se ejecuten correctamente, a menos que el ensamblado que falta se agregue también como referencia del analizador.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Suprimir diagnóstico</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Procesando corrección de supresiones...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Aplicando corrección de supresiones...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Quitar supresiones</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Procesando corrección para quitar supresiones...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Aplicando corrección para quitar supresiones...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">El área de trabajo solo permite abrir documentos en el subproceso de interfaz de usuario.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Esta área de trabajo no admite la actualización de opciones de análisis de Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">Sincronizar {0}</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">Sincronizando con {0}...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio suspendió algunas características avanzadas para mejorar el rendimiento.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">Instalando "{0}"</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">Instalación de "{0}" completada</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">No se pudo instalar el paquete: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Desconocido&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">No</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sí</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Elija una especificación de símbolo y un estilo de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Escriba un título para la regla de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Escriba un título para el estilo de nomenclatura.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Escriba un título para la especificación de símbolo.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Accesibilidades (puede coincidir con cualquiera)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Uso de mayúsculas:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">todo en minúsculas</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">TODO EN MAYÚSCULAS</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">Nombre en camel Case</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">Primera palabra en mayúsculas</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Nombre en Pascal Case</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Gravedad</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Modificadores (deben coincidir todos)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Nombre:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Estilo de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Estilo de nomenclatura:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Las reglas de nomenclatura le permiten definir qué nombres se deben establecer para los conjuntos especiales de símbolos y cómo se debe tratar con los símbolos con nombres incorrectos.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">La primera regla de nomenclatura coincidente de nivel superior se usa de manera predeterminada cuando se asigna un nombre a un símbolo, mientras que todo caso especial se administra según una regla secundaria coincidente.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Título de estilo de nomenclatura:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Regla principal:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Prefijo requerido:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Sufijo requerido:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Identificador de ejemplo:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Tipos de símbolo (pueden coincidir con cualquiera)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Especificación de símbolo:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Título de especificación de símbolo:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Separador de palabras:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">ejemplo</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">identificador</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">Instalar "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">Desinstalando "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">Deinstalación de "{0}" completada</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">Desinstalar "{0}"</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">No se pudo desinstalar el paquete: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Se encontró un error al cargar el proyecto. Se deshabilitaron algunas características del proyecto, como el análisis completo de la solución del proyecto con error y los proyectos que dependen de él.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">No se pudo cargar el proyecto.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Para descubrir la causa del problema, pruebe lo siguiente. 1. Cierre Visual Studio 2. Abra un símbolo del sistema para desarrolladores de Visual Studio. 3. Establezca la variable de entorno “TraceDesignTime” en true (TraceDesignTime=true). 4. Elimine el archivo .suo en el directorio .vs. 5. Reinicie VS desde el símbolo del sistema donde estableció la variable de entorno (devenv). 6. Abra la solución. 7. Compruebe “{0}”y busque las tareas con errores (FAILED).</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Información adicional:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">No se pudo instalar "{0}". Información adicional: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">No se pudo desinstalar "{0}". Información adicional: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">Mover {0} bajo {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">Mover {0} sobre {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">Quitar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">Restaurar {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Volver a habilitar</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Más información</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de marco de trabajo</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Copiar al Portapapeles</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Cerrar</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Parámetros desconocidos&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- Fin del seguimiento de la pila de la excepción interna ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para variables locales, parámetros y miembros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expresiones de acceso a miembro</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">Preferencias de expresión:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Guías de estructura de bloque</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Esquematización</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Mostrar guías para construcciones a nivel de código</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Mostrar guías para regiones de preprocesador y comentarios</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Mostrar guías para construcciones a nivel de declaración</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Mostrar esquematización para construcciones a nivel de código</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Mostrar esquematización para regiones de preprocesador y comentarios</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Mostrar esquematización para construcciones a nivel de declaración</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Preferencias de variable:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Preferir declaración de variable insertada</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar cuerpo de expresiones para los métodos</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Preferencias de bloque de código:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar cuerpo de expresiones para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar cuerpo de expresiones para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar cuerpo de expresiones para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar cuerpo de expresiones para las propiedades</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Algunas reglas de nomenclatura están incompletas. Complételas o quítelas.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Administrar especificaciones</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Reordenar</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Gravedad</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Especificación</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Estilo requerido</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">No se puede eliminar este elemento porque una regla de nomenclatura existente lo usa.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir inicializador de colección</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir expresión de fusión</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Contraer #regions cuando se contraiga a las definiciones</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir propagación nula</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nombre de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Descripción</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Preferencia</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Implementar interfaz o clase abstracta</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Para un símbolo determinado, solo se aplicará la regla superior con una "especificación" concordante. Si se infringe el "estilo requerido" de esa regla, se informará en el nivel de "gravedad" elegido.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">al final</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">Al insertar propiedades, eventos y métodos, colóquelos:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">Con otros miembros de la misma clase</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Preferir llaves</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">Antes que:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Preferir:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">o</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">Tipos integrados</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">En cualquier otra parte</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">El tipo es aparente en la expresión de asignación</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Bajar</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Subir</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Quitar</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Seleccionar miembros</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">Lamentablemente, un proceso utilizado por Visual Studio ha encontrado un error irrecuperable. Recomendamos que guarde su trabajo y luego cierre y reinicie Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Agregar una especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Quitar especificación de símbolo</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Agregar elemento</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Editar elemento</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Quitar elemento</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Agregar una regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Quitar regla de nomenclatura</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">No se puede llamar a VisualStudioWorkspace.TryApplyChanges desde un subproceso en segundo plano.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">preferir propiedades de lanzamiento</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">Al generar propiedades:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Opciones</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">No volver a mostrar</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Preferir la expresión simple "predeterminada"</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir nombres de elementos de tupla inferidos</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Preferir nombres de miembro de tipo anónimo inferidos</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Panel de vista previa</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Análisis</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Atenuar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Atenuando</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Preferir una función local frente a una función anónima</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Preferir declaración de variable desconstruida</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Se encontró una referencia externa</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">No se encontraron referencias a "{0}"</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">No se encontraron resultados para la búsqueda</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propiedades automáticas</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">preferir propiedades automáticas</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">El módulo se descargó.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Habilitar la navegación a orígenes decompilados (experimental)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">El archivo .editorconfig puede invalidar la configuración local definida en esta página que solo se aplica a su máquina. Para configurar estos valores de manera que se desplacen con su solución, use los archivos EditorConfig. Mas información</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Sincronizar vista de clases</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">Analizando “{0}”</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Administrar estilos de nomenclatura</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expresión condicional sobre "if" con asignaciones</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expresión condicional sobre "if" con devoluciones</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Contract.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { internal static class Contract { // Guidance on inlining: // ThrowXxx methods are used heavily across the code base. // Inline their implementation of condition checking but don't inline the code that is only executed on failure. // This approach makes the common path efficient (both execution time and code size) // while keeping the rarely executed code in a separate method. /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail("Unexpected null", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, string message, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail("Unexpected false", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail("Unexpected true", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail(message, lineNumber); } } [DebuggerHidden] [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] public static void Fail(string message = "Unexpected", [CallerLineNumber] int lineNumber = 0) => throw new InvalidOperationException($"{message} - line {lineNumber}"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { internal static class Contract { // Guidance on inlining: // ThrowXxx methods are used heavily across the code base. // Inline their implementation of condition checking but don't inline the code that is only executed on failure. // This approach makes the common path efficient (both execution time and code size) // while keeping the rarely executed code in a separate method. /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail("Unexpected null", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, string message, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail("Unexpected false", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail("Unexpected true", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail(message, lineNumber); } } [DebuggerHidden] [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] public static void Fail(string message = "Unexpected", [CallerLineNumber] int lineNumber = 0) => throw new InvalidOperationException($"{message} - line {lineNumber}"); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">添加 "await"</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">添加 "await" 和 "ConfigureAwait(false)"</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">添加缺少的 using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">添加/删除单行控制语句的括号</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">允许在此项目中使用不安全代码</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">应用表达式/块主体首选项</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">应用隐式/显式类型首选项</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">应用内联 “out” 变量首选项</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">应用语言/框架类型首选项</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">应用 “this.” 资格首选项</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">应用首选的 "using" 放置首选项</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">为 "out" 参数赋值</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">为 "out" 赋值 (在开始处)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">赋值给 "{0}"</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">由于可能出现模式变量声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">更改为 "as" 表达式</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">更改为强制转换</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">与 "{0}" 比较</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">转换为方法</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">转换为正则字符串</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">转换为 "switch" 表达式</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">转换为 \"switch\" 语句</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">转换为逐字字符串</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">声明成可为 null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">修复返回类型</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">内联临时变量</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">检测到冲突。</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">尽可能将私有字段设置为“只读”</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">生成 "ref struct"</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">删除 "in" 关键字</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">删除 "new" 修饰符</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">反向“for”语句</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">简化 lambda 表达式</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">简化所有事件</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">对可访问性修饰符排序</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Unseal 类 "{0}"</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="new">Use recursive patterns</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">警告: 即将在条件方法调用中内联临时内容。</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">警告: 内联临时变量可能会更改代码含义。</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">异步 foreach 语句</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">异步 using 声明</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">外部别名</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;lambda 表达式&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">由于可能出现 lambda 声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">局部变量声明</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;成员名称&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">由于可能导致创建显式命名的匿名类型成员,自动选择已禁用。</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;元素名称&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">由于可能的元组类型元素创建,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;模式变量&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;范围变量&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">由于可能出现范围变量声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">简化名称“{0}”</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">简化成员访问“{0}”</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">删除 "this" 资格</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">可简化名称</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">无法确定要提取的语句的有效范围</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">未返回所有代码路径</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">所选内容不包含有效节点</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">无效的选择。</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">包含无效的选择。</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">所选内容包含语法错误</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">所选内容不能超出预处理器指令。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">所选内容不能包含 yield 语句。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">所选内容不能包含 throw 语句。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">所选内容不能作为常量初始值设定项表达式的一部分。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">所选内容不能包含模式表达式。</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">所选代码位于不安全的上下文中。</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">没有可供提取的有效语句范围</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">弃用的</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">扩展</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">可等待</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">可等待,扩展</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">组织 Using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">插入“await”。</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">使 {0} 返回 Task,而不是 void。</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">将返回类型由 {0} 改为 {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">用 yield return 替代 return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">在“{0}”中生成显示转换运算符</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">在“{0}”中生成隐式转换运算符</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">记录</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">switch 语句</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">switch 语句 case 子句</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">try 块</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">catch 子句</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">filter 子句</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">finally 子句</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">fixed 语句</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">using 声明</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">using 语句</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">lock 语句</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">foreach 语句</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">checked 语句</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">unchecked 语句</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">await 表达式</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">匿名方法</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">from 子句</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">join 子句</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">let 子句</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">where 子句</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">orderby 子句</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">select 子句</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">groupby 子句</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">查询正文</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">into 子句</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">is 模式</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">析构函数</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">元组</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">本地函数</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">out 变量</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref 本地函数或表达式</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">global 语句</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">using 指令</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">事件字段</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">转换运算符</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">析构函数</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">索引器</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">属性 Getter</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">索引器 Getter</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">属性 setter</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">索引器 setter</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">属性目标</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">“{0}”不包含采用许多参数的构造函数。</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">当前上下文中不存在名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">隐藏基成员</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">属性</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">自动选择由于命名空间声明而被禁用。</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;命名空间名称&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">由于类型声明,自动选择被禁用。</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">由于可能有析构声明,禁用了自动选择。</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">将该项目升级为 C# 语言版本“{0}”</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">将所有 C# 项目升级为语言版本“{0}”</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;类名&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;接口名称&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;指定名称&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;结构名称&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">使方法异步</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">使方法异步(保持 void)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;名称&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">因成员声明已禁用自动选择</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(建议名称)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">删除未使用的函数</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">添加括号</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">转换为“foreach”</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">转换为“for”</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">反转 if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">添加 [Obsolete]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">使用 "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">引入 'using' 语句</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">yield break 语句</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">yield return 语句</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">添加 "await"</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">添加 "await" 和 "ConfigureAwait(false)"</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">添加缺少的 using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">添加/删除单行控制语句的括号</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">允许在此项目中使用不安全代码</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">应用表达式/块主体首选项</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">应用隐式/显式类型首选项</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">应用内联 “out” 变量首选项</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">应用语言/框架类型首选项</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">应用 “this.” 资格首选项</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">应用首选的 "using" 放置首选项</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">为 "out" 参数赋值</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">为 "out" 赋值 (在开始处)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">赋值给 "{0}"</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">由于可能出现模式变量声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">更改为 "as" 表达式</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">更改为强制转换</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">与 "{0}" 比较</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">转换为方法</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">转换为正则字符串</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">转换为 "switch" 表达式</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">转换为 \"switch\" 语句</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">转换为逐字字符串</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">声明成可为 null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">修复返回类型</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">内联临时变量</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">检测到冲突。</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">尽可能将私有字段设置为“只读”</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">生成 "ref struct"</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">删除 "in" 关键字</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">删除 "new" 修饰符</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">反向“for”语句</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">简化 lambda 表达式</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">简化所有事件</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">对可访问性修饰符排序</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Unseal 类 "{0}"</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="new">Use recursive patterns</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">警告: 即将在条件方法调用中内联临时内容。</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">警告: 内联临时变量可能会更改代码含义。</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">异步 foreach 语句</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">异步 using 声明</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">外部别名</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;lambda 表达式&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">由于可能出现 lambda 声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">局部变量声明</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;成员名称&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">由于可能导致创建显式命名的匿名类型成员,自动选择已禁用。</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;元素名称&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">由于可能的元组类型元素创建,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;模式变量&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;范围变量&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">由于可能出现范围变量声明,已禁用自动选择。</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">简化名称“{0}”</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">简化成员访问“{0}”</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">删除 "this" 资格</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">可简化名称</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">无法确定要提取的语句的有效范围</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">未返回所有代码路径</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">所选内容不包含有效节点</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">无效的选择。</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">包含无效的选择。</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">所选内容包含语法错误</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">所选内容不能超出预处理器指令。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">所选内容不能包含 yield 语句。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">所选内容不能包含 throw 语句。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">所选内容不能作为常量初始值设定项表达式的一部分。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">所选内容不能包含模式表达式。</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">所选代码位于不安全的上下文中。</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">没有可供提取的有效语句范围</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">弃用的</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">扩展</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">可等待</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">可等待,扩展</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">组织 Using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">插入“await”。</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">使 {0} 返回 Task,而不是 void。</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">将返回类型由 {0} 改为 {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">用 yield return 替代 return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">在“{0}”中生成显示转换运算符</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">在“{0}”中生成隐式转换运算符</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">记录</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">switch 语句</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">switch 语句 case 子句</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">try 块</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">catch 子句</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">filter 子句</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">finally 子句</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">fixed 语句</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">using 声明</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">using 语句</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">lock 语句</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">foreach 语句</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">checked 语句</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">unchecked 语句</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">await 表达式</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">匿名方法</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">from 子句</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">join 子句</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">let 子句</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">where 子句</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">orderby 子句</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">select 子句</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">groupby 子句</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">查询正文</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">into 子句</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">is 模式</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">析构函数</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">元组</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">本地函数</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">out 变量</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref 本地函数或表达式</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">global 语句</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">using 指令</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">事件字段</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">转换运算符</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">析构函数</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">索引器</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">属性 Getter</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">索引器 Getter</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">属性 setter</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">索引器 setter</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">属性目标</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">“{0}”不包含采用许多参数的构造函数。</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">当前上下文中不存在名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">隐藏基成员</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">属性</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">自动选择由于命名空间声明而被禁用。</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;命名空间名称&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">由于类型声明,自动选择被禁用。</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">由于可能有析构声明,禁用了自动选择。</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">将该项目升级为 C# 语言版本“{0}”</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">将所有 C# 项目升级为语言版本“{0}”</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;类名&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;接口名称&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;指定名称&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;结构名称&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">使方法异步</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">使方法异步(保持 void)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;名称&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">因成员声明已禁用自动选择</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(建议名称)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">删除未使用的函数</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">添加括号</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">转换为“foreach”</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">转换为“for”</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">反转 if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">添加 [Obsolete]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">使用 "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">引入 'using' 语句</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">yield break 语句</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">yield return 语句</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/MSBuildTask/InteractiveCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).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. using System.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).ToArray(); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Debugging/IBreakpointResolutionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Debugging { internal interface IBreakpointResolutionService : ILanguageService { Task<BreakpointResolutionResult?> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken = default); Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken = default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Debugging { internal interface IBreakpointResolutionService : ILanguageService { Task<BreakpointResolutionResult?> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken = default); Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeStyle { public class EditorConfigCodeStyleParserTests { [Theory] [InlineData("true:none", true, ReportDiagnostic.Suppress)] [InlineData("true:refactoring", true, ReportDiagnostic.Hidden)] [InlineData("true:silent", true, ReportDiagnostic.Hidden)] [InlineData("true:suggestion", true, ReportDiagnostic.Info)] [InlineData("true:warning", true, ReportDiagnostic.Warn)] [InlineData("true:error", true, ReportDiagnostic.Error)] [InlineData("true", true, ReportDiagnostic.Hidden)] [InlineData("false:none", false, ReportDiagnostic.Suppress)] [InlineData("false:refactoring", false, ReportDiagnostic.Hidden)] [InlineData("false:silent", false, ReportDiagnostic.Hidden)] [InlineData("false:suggestion", false, ReportDiagnostic.Info)] [InlineData("false:warning", false, ReportDiagnostic.Warn)] [InlineData("false:error", false, ReportDiagnostic.Error)] [InlineData("false", false, ReportDiagnostic.Hidden)] [InlineData("*", false, ReportDiagnostic.Hidden)] [InlineData("false:false", false, ReportDiagnostic.Hidden)] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData("true : warning", true, ReportDiagnostic.Warn)] [InlineData("false : warning", false, ReportDiagnostic.Warn)] [InlineData("true : error", true, ReportDiagnostic.Error)] [InlineData("false : error", false, ReportDiagnostic.Error)] public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, ReportDiagnostic severity) { CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, defaultValue: CodeStyleOption2<bool>.Default, out var result); Assert.True(result.Value == isEnabled, $"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}"); Assert.True(result.Notification.Severity == severity, $"Expected {nameof(severity)} to be {severity}, was {result.Notification.Severity}"); } [Theory] [InlineData("never:none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)] [InlineData("always:suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)] [InlineData("for_non_interface_members:warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)] [InlineData("omit_if_default:error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData("never : none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)] [InlineData("always : suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)] [InlineData("for_non_interface_members : warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)] [InlineData("omit_if_default : error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)] public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity) { var storageLocation = CodeStyleOptions2.RequireAccessibilityModifiers.StorageLocations .OfType<EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>>() .Single(); var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, args } }; Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption2<AccessibilityModifiersRequired>), out var parsedCodeStyleOption)); var codeStyleOption = (CodeStyleOption2<AccessibilityModifiersRequired>)parsedCodeStyleOption!; Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value); Assert.Equal(severity, codeStyleOption.Notification.Severity); } [Theory] [InlineData("lf", "\n")] [InlineData("cr", "\r")] [InlineData("crlf", "\r\n")] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData(" lf ", "\n")] [InlineData(" cr ", "\r")] [InlineData(" crlf ", "\r\n")] public void TestParseEditorConfigEndOfLine(string configurationString, string newLine) { var storageLocation = FormattingOptions.NewLine.StorageLocations .OfType<EditorConfigStorageLocation<string>>() .Single(); var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, configurationString } }; Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(string), out var parsedNewLine)); Assert.Equal(newLine, (string?)parsedNewLine); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeStyle { public class EditorConfigCodeStyleParserTests { [Theory] [InlineData("true:none", true, ReportDiagnostic.Suppress)] [InlineData("true:refactoring", true, ReportDiagnostic.Hidden)] [InlineData("true:silent", true, ReportDiagnostic.Hidden)] [InlineData("true:suggestion", true, ReportDiagnostic.Info)] [InlineData("true:warning", true, ReportDiagnostic.Warn)] [InlineData("true:error", true, ReportDiagnostic.Error)] [InlineData("true", true, ReportDiagnostic.Hidden)] [InlineData("false:none", false, ReportDiagnostic.Suppress)] [InlineData("false:refactoring", false, ReportDiagnostic.Hidden)] [InlineData("false:silent", false, ReportDiagnostic.Hidden)] [InlineData("false:suggestion", false, ReportDiagnostic.Info)] [InlineData("false:warning", false, ReportDiagnostic.Warn)] [InlineData("false:error", false, ReportDiagnostic.Error)] [InlineData("false", false, ReportDiagnostic.Hidden)] [InlineData("*", false, ReportDiagnostic.Hidden)] [InlineData("false:false", false, ReportDiagnostic.Hidden)] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData("true : warning", true, ReportDiagnostic.Warn)] [InlineData("false : warning", false, ReportDiagnostic.Warn)] [InlineData("true : error", true, ReportDiagnostic.Error)] [InlineData("false : error", false, ReportDiagnostic.Error)] public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, ReportDiagnostic severity) { CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, defaultValue: CodeStyleOption2<bool>.Default, out var result); Assert.True(result.Value == isEnabled, $"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}"); Assert.True(result.Notification.Severity == severity, $"Expected {nameof(severity)} to be {severity}, was {result.Notification.Severity}"); } [Theory] [InlineData("never:none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)] [InlineData("always:suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)] [InlineData("for_non_interface_members:warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)] [InlineData("omit_if_default:error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData("never : none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)] [InlineData("always : suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)] [InlineData("for_non_interface_members : warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)] [InlineData("omit_if_default : error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)] public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity) { var storageLocation = CodeStyleOptions2.RequireAccessibilityModifiers.StorageLocations .OfType<EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>>() .Single(); var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, args } }; Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption2<AccessibilityModifiersRequired>), out var parsedCodeStyleOption)); var codeStyleOption = (CodeStyleOption2<AccessibilityModifiersRequired>)parsedCodeStyleOption!; Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value); Assert.Equal(severity, codeStyleOption.Notification.Severity); } [Theory] [InlineData("lf", "\n")] [InlineData("cr", "\r")] [InlineData("crlf", "\r\n")] [WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")] [InlineData(" lf ", "\n")] [InlineData(" cr ", "\r")] [InlineData(" crlf ", "\r\n")] public void TestParseEditorConfigEndOfLine(string configurationString, string newLine) { var storageLocation = FormattingOptions.NewLine.StorageLocations .OfType<EditorConfigStorageLocation<string>>() .Single(); var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, configurationString } }; Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(string), out var parsedNewLine)); Assert.Equal(newLine, (string?)parsedNewLine); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/OmniSharp/ExtractInterface/IOmniSharpExtractInterfaceOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractInterface { internal interface IOmniSharpExtractInterfaceOptionsService { // OmniSharp only uses these two arguments from the full IExtractInterfaceOptionsService Task<OmniSharpExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( List<ISymbol> extractableMembers, string defaultInterfaceName); } internal class OmniSharpExtractInterfaceOptionsResult { public enum OmniSharpExtractLocation { SameFile, NewFile } public bool IsCancelled { get; } public ImmutableArray<ISymbol> IncludedMembers { get; } public string InterfaceName { get; } public string FileName { get; } public OmniSharpExtractLocation Location { get; } public OmniSharpExtractInterfaceOptionsResult(bool isCancelled, ImmutableArray<ISymbol> includedMembers, string interfaceName, string fileName, OmniSharpExtractLocation location) { IsCancelled = isCancelled; IncludedMembers = includedMembers; InterfaceName = interfaceName; Location = location; FileName = fileName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractInterface { internal interface IOmniSharpExtractInterfaceOptionsService { // OmniSharp only uses these two arguments from the full IExtractInterfaceOptionsService Task<OmniSharpExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( List<ISymbol> extractableMembers, string defaultInterfaceName); } internal class OmniSharpExtractInterfaceOptionsResult { public enum OmniSharpExtractLocation { SameFile, NewFile } public bool IsCancelled { get; } public ImmutableArray<ISymbol> IncludedMembers { get; } public string InterfaceName { get; } public string FileName { get; } public OmniSharpExtractLocation Location { get; } public OmniSharpExtractInterfaceOptionsResult(bool isCancelled, ImmutableArray<ISymbol> includedMembers, string interfaceName, string fileName, OmniSharpExtractLocation location) { IsCancelled = isCancelled; IncludedMembers = includedMembers; InterfaceName = interfaceName; Location = location; FileName = fileName; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/AnalyzerRunner/AssemblyLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using Microsoft.CodeAnalysis; namespace AnalyzerRunner { internal class AssemblyLoader : IAnalyzerAssemblyLoader { public static AssemblyLoader Instance = new AssemblyLoader(); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { return Assembly.LoadFrom(fullPath); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using Microsoft.CodeAnalysis; namespace AnalyzerRunner { internal class AssemblyLoader : IAnalyzerAssemblyLoader { public static AssemblyLoader Instance = new AssemblyLoader(); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { return Assembly.LoadFrom(fullPath); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/xlf/ExternalAccessFSharpResources.cs.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="cs" original="../ExternalAccessFSharpResources.resx"> <body> <trans-unit id="AddAssemblyReference"> <source>Add an assembly reference to '{0}'</source> <target state="translated">Přidat odkaz na sestavení do {0}</target> <note /> </trans-unit> <trans-unit id="AddNewKeyword"> <source>Add 'new' keyword</source> <target state="translated">Přidat klíčové slovo new</target> <note /> </trans-unit> <trans-unit id="AddProjectReference"> <source>Add a project reference to '{0}'</source> <target state="translated">Přidat odkaz na projekt do {0}</target> <note /> </trans-unit> <trans-unit id="CannotDetermineSymbol"> <source>Cannot determine the symbol under the caret</source> <target state="translated">Nelze určit symbol pod kurzorem.</target> <note /> </trans-unit> <trans-unit id="CannotNavigateUnknown"> <source>Cannot navigate to the requested location</source> <target state="translated">Na požadované umístění nelze přejít.</target> <note /> </trans-unit> <trans-unit id="ExceptionsHeader"> <source>Exceptions:</source> <target state="translated">Výjimky:</target> <note /> </trans-unit> <trans-unit id="FSharpDisposablesClassificationType"> <source>F# Disposable Types</source> <target state="translated">F# – uvolnitelné typy</target> <note /> </trans-unit> <trans-unit id="FSharpFunctionsOrMethodsClassificationType"> <source>F# Functions / Methods</source> <target state="translated">F# – funkce/metody</target> <note /> </trans-unit> <trans-unit id="FSharpMutableVarsClassificationType"> <source>F# Mutable Variables / Reference Cells</source> <target state="translated">F# – měnitelné proměnné / buňky odkazu</target> <note /> </trans-unit> <trans-unit id="FSharpPrintfFormatClassificationType"> <source>F# Printf Format</source> <target state="translated">F# – formát printf</target> <note /> </trans-unit> <trans-unit id="FSharpPropertiesClassificationType"> <source>F# Properties</source> <target state="translated">F# – vlastnosti</target> <note /> </trans-unit> <trans-unit id="GenericParametersHeader"> <source>Generic parameters:</source> <target state="translated">Obecné parametry:</target> <note /> </trans-unit> <trans-unit id="ImplementInterface"> <source>Implement interface</source> <target state="translated">Implementujte rozhraní.</target> <note /> </trans-unit> <trans-unit id="ImplementInterfaceWithoutTypeAnnotation"> <source>Implement interface without type annotation</source> <target state="translated">Implementovat rozhraní bez anotace typu</target> <note /> </trans-unit> <trans-unit id="LocatingSymbol"> <source>Locating the symbol under the caret...</source> <target state="translated">Vyhledává se symbol pod kurzorem...</target> <note /> </trans-unit> <trans-unit id="NameCanBeSimplified"> <source>Name can be simplified.</source> <target state="translated">Název může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="NavigateToFailed"> <source>Navigate to symbol failed: {0}</source> <target state="translated">Nepovedlo se přejít na symbol: {0}</target> <note /> </trans-unit> <trans-unit id="NavigatingTo"> <source>Navigating to symbol...</source> <target state="translated">Přechází se na symbol...</target> <note /> </trans-unit> <trans-unit id="PrefixValueNameWithUnderscore"> <source>Prefix '{0}' with underscore</source> <target state="translated">Předpona {0} s podtržítkem</target> <note /> </trans-unit> <trans-unit id="RemoveUnusedOpens"> <source>Remove unused open declarations</source> <target state="translated">Odebrat nepoužívané otevřené deklarace</target> <note /> </trans-unit> <trans-unit id="RenameValueToDoubleUnderscore"> <source>Rename '{0}' to '__'</source> <target state="translated">Přejmenovat {0} na __</target> <note /> </trans-unit> <trans-unit id="RenameValueToUnderscore"> <source>Rename '{0}' to '_'</source> <target state="translated">Přejmenovat {0} na _</target> <note /> </trans-unit> <trans-unit id="SimplifyName"> <source>Simplify name</source> <target state="translated">Zjednodušit název</target> <note /> </trans-unit> <trans-unit id="TheValueIsUnused"> <source>The value is unused</source> <target state="translated">Hodnota se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="UnusedOpens"> <source>Open declaration can be removed.</source> <target state="translated">Otevřenou deklaraci je možné odebrat.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="cs" original="../ExternalAccessFSharpResources.resx"> <body> <trans-unit id="AddAssemblyReference"> <source>Add an assembly reference to '{0}'</source> <target state="translated">Přidat odkaz na sestavení do {0}</target> <note /> </trans-unit> <trans-unit id="AddNewKeyword"> <source>Add 'new' keyword</source> <target state="translated">Přidat klíčové slovo new</target> <note /> </trans-unit> <trans-unit id="AddProjectReference"> <source>Add a project reference to '{0}'</source> <target state="translated">Přidat odkaz na projekt do {0}</target> <note /> </trans-unit> <trans-unit id="CannotDetermineSymbol"> <source>Cannot determine the symbol under the caret</source> <target state="translated">Nelze určit symbol pod kurzorem.</target> <note /> </trans-unit> <trans-unit id="CannotNavigateUnknown"> <source>Cannot navigate to the requested location</source> <target state="translated">Na požadované umístění nelze přejít.</target> <note /> </trans-unit> <trans-unit id="ExceptionsHeader"> <source>Exceptions:</source> <target state="translated">Výjimky:</target> <note /> </trans-unit> <trans-unit id="FSharpDisposablesClassificationType"> <source>F# Disposable Types</source> <target state="translated">F# – uvolnitelné typy</target> <note /> </trans-unit> <trans-unit id="FSharpFunctionsOrMethodsClassificationType"> <source>F# Functions / Methods</source> <target state="translated">F# – funkce/metody</target> <note /> </trans-unit> <trans-unit id="FSharpMutableVarsClassificationType"> <source>F# Mutable Variables / Reference Cells</source> <target state="translated">F# – měnitelné proměnné / buňky odkazu</target> <note /> </trans-unit> <trans-unit id="FSharpPrintfFormatClassificationType"> <source>F# Printf Format</source> <target state="translated">F# – formát printf</target> <note /> </trans-unit> <trans-unit id="FSharpPropertiesClassificationType"> <source>F# Properties</source> <target state="translated">F# – vlastnosti</target> <note /> </trans-unit> <trans-unit id="GenericParametersHeader"> <source>Generic parameters:</source> <target state="translated">Obecné parametry:</target> <note /> </trans-unit> <trans-unit id="ImplementInterface"> <source>Implement interface</source> <target state="translated">Implementujte rozhraní.</target> <note /> </trans-unit> <trans-unit id="ImplementInterfaceWithoutTypeAnnotation"> <source>Implement interface without type annotation</source> <target state="translated">Implementovat rozhraní bez anotace typu</target> <note /> </trans-unit> <trans-unit id="LocatingSymbol"> <source>Locating the symbol under the caret...</source> <target state="translated">Vyhledává se symbol pod kurzorem...</target> <note /> </trans-unit> <trans-unit id="NameCanBeSimplified"> <source>Name can be simplified.</source> <target state="translated">Název může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="NavigateToFailed"> <source>Navigate to symbol failed: {0}</source> <target state="translated">Nepovedlo se přejít na symbol: {0}</target> <note /> </trans-unit> <trans-unit id="NavigatingTo"> <source>Navigating to symbol...</source> <target state="translated">Přechází se na symbol...</target> <note /> </trans-unit> <trans-unit id="PrefixValueNameWithUnderscore"> <source>Prefix '{0}' with underscore</source> <target state="translated">Předpona {0} s podtržítkem</target> <note /> </trans-unit> <trans-unit id="RemoveUnusedOpens"> <source>Remove unused open declarations</source> <target state="translated">Odebrat nepoužívané otevřené deklarace</target> <note /> </trans-unit> <trans-unit id="RenameValueToDoubleUnderscore"> <source>Rename '{0}' to '__'</source> <target state="translated">Přejmenovat {0} na __</target> <note /> </trans-unit> <trans-unit id="RenameValueToUnderscore"> <source>Rename '{0}' to '_'</source> <target state="translated">Přejmenovat {0} na _</target> <note /> </trans-unit> <trans-unit id="SimplifyName"> <source>Simplify name</source> <target state="translated">Zjednodušit název</target> <note /> </trans-unit> <trans-unit id="TheValueIsUnused"> <source>The value is unused</source> <target state="translated">Hodnota se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="UnusedOpens"> <source>Open declaration can be removed.</source> <target state="translated">Otevřenou deklaraci je možné odebrat.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/CodeGen/DebugDocumentProvider.cs
// Licensed to the .NET Foundation under one or more 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.CodeGen { internal delegate Cci.DebugSourceDocument DebugDocumentProvider(string path, string basePath); }
// Licensed to the .NET Foundation under one or more 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.CodeGen { internal delegate Cci.DebugSourceDocument DebugDocumentProvider(string path, string basePath); }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpErrorListNetCore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.GenerateVariable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateVariable { public class GenerateVariableTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { private const int FieldIndex = 0; private const int ReadonlyFieldIndex = 1; private const int PropertyIndex = 2; private const int LocalIndex = 3; private const int Parameter = 4; private const int ParameterAndOverrides = 5; public GenerateVariableTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpGenerateVariableCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); // specify all options explicitly to override defaults. private OptionsCollection ImplicitTypingEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleLowercaseIdentifier1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { private object goo; void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleLowercaseIdentifier2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { private readonly object goo; void Method() { goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestTestSimpleLowercaseIdentifier3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { public object goo { get; private set; } void Method() { goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { public object Goo { get; private set; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { private object Goo; void Method() { Goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { private readonly object Goo; void Method() { Goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleRead1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { Method([|goo|]); } }", @"class Class { private int goo; void Method(int i) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleReadWithTopLevelNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Class { void Method(string? s) { Method([|goo|]); } }", @"#nullable enable class Class { private string? goo; void Method(string? s) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleReadWithNestedNullability() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Collections.Generic; class Class { void Method(IEnumerable<string?> s) { Method([|goo|]); } }", @"#nullable enable using System.Collections.Generic; class Class { private IEnumerable<string?> goo; void Method(IEnumerable<string?> s) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWriteCount() { await TestExactActionSetOfferedAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_property_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWriteInOverrideCount() { await TestExactActionSetOfferedAsync( @" abstract class Base { public abstract void Method(int i); } class Class : Base { public override void Method(int i) { [|goo|] = 1; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_property_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0_and_overrides_implementations, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWrite1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", @"class Class { private int goo; void Method(int i) { goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWrite2() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", @"class Class { public int goo { get; private set; } void Method(int i) { goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInRef() { await TestInRegularAndScriptAsync( @"class Class { void Method(ref int i) { Method(ref this.[|goo|]); } }", @"class Class { private int goo; void Method(ref int i) { Method(ref this.[|goo|]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInRef() { await TestInRegularAndScriptAsync( @" using System; class Class { void Method(ref int i) { Method(ref this.[|goo|]); } }", @" using System; class Class { public ref int goo => throw new NotImplementedException(); void Method(ref int i) { Method(ref this.goo); } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInIn() { await TestInRegularAndScriptAsync( @" using System; class Class { void Method(in int i) { Method(in this.[|goo|]); } }", @" using System; class Class { public ref readonly int goo => throw new NotImplementedException(); void Method(in int i) { Method(in this.goo); } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInRef1() { await TestInRegularAndScriptAsync( @"class Class { void Method(ref int i) { Method(ref [|goo|]); } }", @"class Class { private int goo; void Method(ref int i) { Method(ref goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInOutCodeActionCount() { await TestExactActionSetOfferedAsync( @"class Class { void Method(out int i) { Method(out [|goo|]); } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInOut1() { await TestInRegularAndScriptAsync( @"class Class { void Method(out int i) { Method(out [|goo|]); } }", @"class Class { private int goo; void Method(out int i) { Method(out goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember1() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { private static object goo; static void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember2() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { private static readonly object goo; static void Method() { goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember3() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { public static object goo { get; private set; } static void Method() { goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { private object goo; void Method() { this.goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { private readonly object goo; void Method() { this.goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { public object goo { get; private set; } void Method() { this.goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenInstance1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|] = 1; } }", @"class Class { private int goo; void Method() { this.goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenInstance2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|] = 1; } }", @"class Class { public int goo { get; private set; } void Method() { this.goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { private static object goo; void Method() { Class.goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { private static readonly object goo; void Method() { Class.goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { public static object goo { get; private set; } void Method() { Class.goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenStatic1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|] = 1; } }", @"class Class { private static int goo; void Method() { Class.goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenStatic2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|] = 1; } }", @"class Class { public static int goo { get; private set; } void Method() { Class.goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoSibling1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { new D().[|goo|]; } } class D { }", @"class Class { void Method() { new D().goo; } } class D { internal object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoOuter1() { await TestInRegularAndScriptAsync( @"class Outer { class Class { void Method() { new Outer().[|goo|]; } } }", @"class Outer { private object goo; class Class { void Method() { new Outer().goo; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoDerived1() { await TestInRegularAndScriptAsync( @"class Class : Base { void Method(Base b) { b.[|goo|]; } } class Base { }", @"class Class : Base { void Method(Base b) { b.goo; } } class Base { internal object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateStaticIntoDerived1() { await TestInRegularAndScriptAsync( @"class Class : Base { void Method(Base b) { Base.[|goo|]; } } class Base { }", @"class Class : Base { void Method(Base b) { Base.goo; } } class Base { protected static object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterfaceFixCount() { await TestActionCountAsync( @"class Class { void Method(I i) { i.[|goo|]; } } interface I { }", count: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterface1() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|]; } } interface I { }", @"class Class { void Method(I i) { i.Goo; } } interface I { object Goo { get; set; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterface2() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|]; } } interface I { }", @"class Class { void Method(I i) { i.Goo; } } interface I { object Goo { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateStaticIntoInterfaceMissing() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method(I i) { I.[|Goo|]; } } interface I { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateWriteIntoInterfaceFixCount() { await TestActionCountAsync( @"class Class { void Method(I i) { i.[|Goo|] = 1; } } interface I { }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateWriteIntoInterface1() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|] = 1; } } interface I { }", @"class Class { void Method(I i) { i.Goo = 1; } } interface I { int Goo { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericType() { await TestInRegularAndScriptAsync( @"class Class<T> { void Method(T t) { [|goo|] = t; } }", @"class Class<T> { private T goo; void Method(T t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod1() { await TestInRegularAndScriptAsync( @"class Class { void Method<T>(T t) { [|goo|] = t; } }", @"class Class { private object goo; void Method<T>(T t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod2() { await TestInRegularAndScriptAsync( @"class Class { void Method<T>(IList<T> t) { [|goo|] = t; } }", @"class Class { private IList<object> goo; void Method<T>(IList<T> t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldBeforeFirstField() { await TestInRegularAndScriptAsync( @"class Class { int i; void Method() { [|goo|]; } }", @"class Class { int i; private object goo; void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldAfterLastField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } int i; }", @"class Class { void Method() { goo; } int i; private object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastField1() { await TestInRegularAndScriptAsync( @"class Class { int Bar; void Method() { [|Goo|]; } }", @"class Class { int Bar; public object Goo { get; private set; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } int Bar; }", @"class Class { void Method() { Goo; } int Bar; public object Goo { get; private set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyBeforeFirstProperty() { await TestInRegularAndScriptAsync( @"class Class { int Quux { get; } void Method() { [|Goo|]; } }", @"class Class { public object Goo { get; private set; } int Quux { get; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyBeforeFirstPropertyEvenWithField1() { await TestInRegularAndScriptAsync( @"class Class { int Bar; int Quux { get; } void Method() { [|Goo|]; } }", @"class Class { int Bar; public object Goo { get; private set; } int Quux { get; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastPropertyEvenWithField2() { await TestInRegularAndScriptAsync( @"class Class { int Quux { get; } int Bar; void Method() { [|Goo|]; } }", @"class Class { int Quux { get; } public object Goo { get; private set; } int Bar; void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInInvocation() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInObjectCreation() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { new [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInTypeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|].B a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.[|B|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B.C|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B|].C a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.B.[|C|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|].B.C a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.[|B|].C a; } }"); } [WorkItem(539336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInAttribute() { await TestMissingInRegularAndScriptAsync( @"[[|A|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A|].B] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.[|B|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B.C|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B|].C] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.B.[|C|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A|].B.C] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.B.[|C|]] class Class { }"); } [WorkItem(539340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539340")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSpansField() { await TestSpansAsync( @"class C { void M() { this.[|Goo|] }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|]; }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 + 2 }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 + 2; }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] += Bar() }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] += Bar(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInSimpleLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<string, int> f = x => [|goo|]; } }", @"using System; class Program { private static int goo; static void Main(string[] args) { Func<string, int> f = x => goo; } }", FieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInParenthesizedLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int> f = () => [|goo|]; } }", @"using System; class Program { private static int goo; static void Main(string[] args) { Func<int> f = () => goo; } }", FieldIndex); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInAsyncTaskOfTSimpleLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task<int>> f = async x => [|goo|]; } }", @"using System; using System.Threading.Tasks; class Program { private static int goo; static void Main(string[] args) { Func<string, Task<int>> f = async x => goo; } }", FieldIndex); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInAsyncTaskOfTParenthesizedLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<Task<int>> f = async () => [|goo|]; } }", @"using System; using System.Threading.Tasks; class Program { private static int goo; static void Main(string[] args) { Func<Task<int>> f = async () => goo; } }", FieldIndex); } [WorkItem(539427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539427")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromLambda() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = () => { return 2 }; } }", @"using System; class Class { private Func<int> goo; void Method(int i) { goo = () => { return 2 }; } }"); } // TODO: Move to TypeInferrer.InferTypes, or something [WorkItem(539466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInMethodOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { System.Console.WriteLine([|goo|]); } }", @"class Class { private bool goo; void Method(int i) { System.Console.WriteLine(goo); } }"); } // TODO: Move to TypeInferrer.InferTypes, or something [WorkItem(539466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInMethodOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { System.Console.WriteLine(this.[|goo|]); } }", @"class Class { private bool goo; void Method(int i) { System.Console.WriteLine(this.goo); } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty1() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { get; set; } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { get; set; } } interface ITest { bool SomeProp { get; set; } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty2() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { } } interface ITest { bool SomeProp { get; set; } }", index: ReadonlyFieldIndex); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty3() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { } } interface ITest { bool SomeProp { get; } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty4() { await TestMissingInRegularAndScriptAsync( @"class Class { bool ITest.[|SomeProp|] { } } interface ITest { }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty5() { await TestMissingInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { bool SomeProp { get; } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEscapedName() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|@goo|]; } }", @"class Class { private object goo; void Method() { @goo; } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEscapedKeyword() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|@int|]; } }", @"class Class { private object @int; void Method() { @int; } }"); } [WorkItem(539529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539529")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestRefLambda() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|test|] = (ref int x) => x = 10; } }", @"class Class { private object test; void Method() { test = (ref int x) => x = 10; } }"); } [WorkItem(539595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539595")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnError() { await TestMissingInRegularAndScriptAsync( @"class Class { void F<U, V>(U u1, V v1) { Goo<string, int>([|u1|], u2); } }"); } [WorkItem(539571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539571")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNameSimplification() { await TestInRegularAndScriptAsync( @"namespace TestNs { class Program { class Test { void Meth() { Program.[|blah|] = new Test(); } } } }", @"namespace TestNs { class Program { private static Test blah; class Test { void Meth() { Program.blah = new Test(); } } } }"); } [WorkItem(539717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPostIncrement() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|i|]++; } }", @"class Program { private static int i; static void Main(string[] args) { i++; } }"); } [WorkItem(539717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreDecrement() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { --[|i|]; } }", @"class Program { private static int i; static void Main(string[] args) { --i; } }"); } [WorkItem(539738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539738")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoScript() { await TestAsync( @"using C; static class C { } C.[|i|] ++ ;", @"using C; static class C { internal static int i; } C.i ++ ;", parseOptions: Options.Script); } [WorkItem(539558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539558")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5565() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|Goo|]#(); } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { public static object Goo { get; private set; } static void Main(string[] args) { Goo#(); } }"); } [WorkItem(539536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539536")] [Fact(Skip = "Tuples"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5538() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { new([|goo|])(); } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { public static object goo { get; private set; } static void Main(string[] args) { new(goo)(); } }", index: PropertyIndex); } [WorkItem(539665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5697() { await TestInRegularAndScriptAsync( @"class C { } class D { void M() { C.[|P|] = 10; } } ", @"class C { public static int P { get; internal set; } } class D { void M() { C.P = 10; } } "); } [WorkItem(539793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIncrement() { await TestExactActionSetOfferedAsync( @"class Program { static void Main() { [|p|]++; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "p", "Program"), string.Format(FeaturesResources.Generate_property_1_0, "p", "Program"), string.Format(FeaturesResources.Generate_local_0, "p"), string.Format(FeaturesResources.Generate_parameter_0, "p") }); await TestInRegularAndScriptAsync( @"class Program { static void Main() { [|p|]++; } }", @"class Program { private static int p; static void Main() { p++; } }"); } [WorkItem(539834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539834")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task TestNotInGoto() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { goto [|goo|]; } }"); } [WorkItem(539826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539826")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnLeftOfDot() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { [|goo|].ToString(); } }", @"class Program { private static object goo; static void Main() { goo.ToString(); } }"); } [WorkItem(539840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotBeforeAlias() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|global|]::System.String s; } }"); } [WorkItem(539871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539871")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnGenericName() { await TestMissingInRegularAndScriptAsync( @"class C<T> { public delegate void Goo<R>(R r); static void M() { Goo<T> r = [|Goo<T>|]; } }"); } [WorkItem(539934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539934")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnDelegateAddition() { await TestAsync( @"class C { delegate void D(); void M() { D d = [|M1|] + M2; } }", @"class C { private D M1 { get; set; } delegate void D(); void M() { D d = M1 + M2; } }", parseOptions: null); } [WorkItem(539986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestReferenceTypeParameter1() { await TestInRegularAndScriptAsync( @"class C<T> { public void Test() { C<T> c = A.[|M|]; } } class A { }", @"class C<T> { public void Test() { C<T> c = A.M; } } class A { public static C<object> M { get; internal set; } }"); } [WorkItem(539986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestReferenceTypeParameter2() { await TestInRegularAndScriptAsync( @"class C<T> { public void Test() { C<T> c = A.[|M|]; } class A { } }", @"class C<T> { public void Test() { C<T> c = A.M; } class A { public static C<T> M { get; internal set; } } }"); } [WorkItem(540159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540159")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEmptyIdentifierName() { await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int i = [|@|] } }"); await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int i = [|@|]} }"); } [WorkItem(541194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541194")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestForeachVar() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var v in [|list|]) { } } }", @"using System.Collections.Generic; class C { private IEnumerable<object> list; void M() { foreach (var v in list) { } } }"); } [WorkItem(541265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExtensionMethodUsedAsInstance() { await TestAsync( @"using System; class C { public static void Main() { string s = ""Hello""; [|f|] = s.ExtensionMethod; } } public static class MyExtension { public static int ExtensionMethod(this String s) { return s.Length; } }", @"using System; class C { private static Func<int> f; public static void Main() { string s = ""Hello""; f = s.ExtensionMethod; } } public static class MyExtension { public static int ExtensionMethod(this String s) { return s.Length; } }", parseOptions: null); } [WorkItem(541549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541549")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestDelegateInvoke() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int, int> f = x => x + 1; f([|x|]); } }", @"using System; class Program { private static int x; static void Main(string[] args) { Func<int, int> f = x => x + 1; f(x); } }"); } [WorkItem(541597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestComplexAssign1() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|a|] = a + 10; } }", @"class Program { private static int a; static void Main(string[] args) { a = a + 10; } }"); } [WorkItem(541597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestComplexAssign2() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { a = [|a|] + 10; } }", @"class Program { private static int a; static void Main(string[] args) { a = a + 10; } }"); } [WorkItem(541659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541659")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestTypeNamedVar() { await TestInRegularAndScriptAsync( @"using System; class Program { public static void Main() { var v = [|p|]; } } class var { }", @"using System; class Program { private static var p; public static void Main() { var v = p; } } class var { }"); } [WorkItem(541675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestStaticExtensionMethodArgument() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { MyExtension.ExMethod([|ss|]); } } static class MyExtension { public static int ExMethod(this string s) { return s.Length; } }", @"using System; class Program { private static string ss; static void Main(string[] args) { MyExtension.ExMethod(ss); } } static class MyExtension { public static int ExMethod(this string s) { return s.Length; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task SpeakableTopLevelStatementType() { await TestMissingAsync(@" [|P|] = 10; partial class Program { }"); } [WorkItem(539675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBeforeCommentBetweenMembers1() { await TestInRegularAndScriptAsync( @"class Program { //method static void Main(string[] args) { [|P|] = 10; } }", @"class Program { public static int P { get; private set; } //method static void Main(string[] args) { P = 10; } }"); } [WorkItem(539675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBeforeCommentBetweenMembers2() { await TestInRegularAndScriptAsync( @"class Program { //method static void Main(string[] args) { [|P|] = 10; } }", @"class Program { private static int P; //method static void Main(string[] args) { P = 10; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBetweenMembers1() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|P|] = 10; } }", @"class Program { private static int P; static void Main(string[] args) { P = 10; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBetweenMembers2() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|P|] = 10; } }", @"class Program { public static int P { get; private set; } static void Main(string[] args) { P = 10; } }", index: 0); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontAddBlankLineBetweenFields() { await TestInRegularAndScriptAsync( @"class Program { private static int P; static void Main(string[] args) { P = 10; [|A|] = 9; } }", @"class Program { private static int P; private static int A; static void Main(string[] args) { P = 10; A = 9; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontAddBlankLineBetweenAutoProperties() { await TestInRegularAndScriptAsync( @"class Program { public static int P { get; private set; } static void Main(string[] args) { P = 10; [|A|] = 9; } }", @"class Program { public static int P { get; private set; } public static int A { get; private set; } static void Main(string[] args) { P = 10; A = 9; } }", index: 0); } [WorkItem(539665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIntoEmptyClass() { await TestInRegularAndScriptAsync( @"class C { } class D { void M() { C.[|P|] = 10; } }", @"class C { public static int P { get; internal set; } } class D { void M() { C.P = 10; } }"); } [WorkItem(540595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540595")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInScript() { await TestAsync( @"[|Goo|]", @"object Goo { get; private set; } Goo", parseOptions: Options.Script); } [WorkItem(542535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542535")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantInParameterValue() { const string Initial = @"class C { const int y = 1 ; public void Goo ( bool x = [|undeclared|] ) { } } "; await TestActionCountAsync( Initial, count: 1); await TestInRegularAndScriptAsync( Initial, @"class C { const int y = 1 ; private const bool undeclared; public void Goo ( bool x = undeclared ) { } } "); } [WorkItem(542900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAttributeNamedArgument1() { await TestInRegularAndScriptAsync( @"using System; class ProgramAttribute : Attribute { [Program([|Name|] = 0)] static void Main(string[] args) { } }", @"using System; class ProgramAttribute : Attribute { public int Name { get; set; } [Program(Name = 0)] static void Main(string[] args) { } }"); } [WorkItem(542900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAttributeNamedArgument2() { await TestInRegularAndScriptAsync( @"using System; class ProgramAttribute : Attribute { [Program([|Name|] = 0)] static void Main(string[] args) { } }", @"using System; class ProgramAttribute : Attribute { public int Name; [Program(Name = 0)] static void Main(string[] args) { } }", index: ReadonlyFieldIndex); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility1_InternalPrivate() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } private class C { } }", @"class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility2_InternalProtected() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } protected class C { } }", @"class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility3_InternalInternal() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } internal class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility4_InternalProtectedInternal() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } protected internal class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility5_InternalPublic() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } public class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } public class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility6_PublicInternal() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } internal class C { } }", @"public class Program { internal static C P { get; private set; } public static void Main() { C c = P; } internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility7_PublicProtectedInternal() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } protected internal class C { } }", @"public class Program { protected internal static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility8_PublicProtected() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } protected class C { } }", @"public class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility9_PublicPrivate() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } private class C { } }", @"public class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility10_PrivatePrivate() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } private class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } private class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility11_PrivateProtected() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } protected class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility12_PrivateProtectedInternal() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } protected internal class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility13_PrivateInternal() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility14_ProtectedPrivate() { await TestAsync( @"class outer { protected class Program { public static void Main() { C c = [|P|]; } private class C { } } }", @"class outer { protected class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility15_ProtectedInternal() { await TestAsync( @"class outer { protected class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { protected class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility16_ProtectedInternalProtected() { await TestAsync( @"class outer { protected internal class Program { public static void Main() { C c = [|P|]; } protected class C { } } }", @"class outer { protected internal class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility17_ProtectedInternalInternal() { await TestAsync( @"class outer { protected internal class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { protected internal class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(543153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543153")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAnonymousObjectInitializer1() { await TestInRegularAndScriptAsync( @"class C { void M() { var a = new { x = 5 }; a = new { x = [|HERE|] }; } }", @"class C { private int HERE; void M() { var a = new { x = 5 }; a = new { x = HERE }; } }", index: ReadonlyFieldIndex); } [WorkItem(543124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543124")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoGenerationIntoAnonymousType() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { var v = new { }; bool b = v.[|Bar|]; } }"); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOfferedForBoundParametersOfOperators() { await TestMissingInRegularAndScriptAsync( @"class Program { public Program(string s) { } static void Main(string[] args) { Program p = """"; } public static implicit operator Program(string str) { return new Program([|str|]); } }"); } [WorkItem(544175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544175")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnNamedParameterName1() { await TestMissingInRegularAndScriptAsync( @"using System; class class1 { public void Test() { Goo([|x|]: x); } public string Goo(int x) { } }"); } [WorkItem(544271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544271")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnNamedParameterName2() { await TestMissingInRegularAndScriptAsync( @"class Goo { public Goo(int a = 42) { } } class DogBed : Goo { public DogBed(int b) : base([|a|]: b) { } }"); } [WorkItem(544164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544164")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = 24 }; } }", @"class Goo { public int Gibberish { get; internal set; } } class Bar { void goo() { var c = new Goo { Gibberish = 24 }; } }"); } [WorkItem(49294, "https://github.com/dotnet/roslyn/issues/49294")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyInWithInitializer() { await TestInRegularAndScriptAsync( @"record Goo { } class Bar { void goo(Goo g) { var c = g with { [|Gibberish|] = 24 }; } }", @"record Goo { public int Gibberish { get; internal set; } } class Bar { void goo(Goo g) { var c = g with { Gibberish = 24 }; } }"); } [WorkItem(13166, "https://github.com/dotnet/roslyn/issues/13166")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnNestedObjectInitializer() { await TestInRegularAndScriptAsync( @"public class Inner { } public class Outer { public Inner Inner { get; set; } = new Inner(); public static Outer X() => new Outer { Inner = { [|InnerValue|] = 5 } }; }", @"public class Inner { public int InnerValue { get; internal set; } } public class Outer { public Inner Inner { get; set; } = new Inner(); public static Outer X() => new Outer { Inner = { InnerValue = 5 } }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer1() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = Gibberish }; } }", @"class Goo { public object Gibberish { get; internal set; } } class Bar { void goo() { var c = new Goo { Gibberish = Gibberish }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer2() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|Gibberish|] }; } }", @"class Goo { } class Bar { public object Gibberish { get; private set; } void goo() { var c = new Goo { Gibberish = Gibberish }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = 24 }; } }", @"class Goo { internal int Gibberish; } class Bar { void goo() { var c = new Goo { Gibberish = 24 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer1() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = Gibberish }; } }", @"class Goo { internal object Gibberish; } class Bar { void goo() { var c = new Goo { Gibberish = Gibberish }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer2() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|Gibberish|] }; } }", @"class Goo { } class Bar { private object Gibberish; void goo() { var c = new Goo { Gibberish = Gibberish }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnlyPropertyAndFieldOfferedForObjectInitializer() { await TestActionCountAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { . [|Gibberish|] = 24 }; } }", 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInObjectInitializerValue() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|blah|] }; } }", @"class Goo { } class Bar { void goo() { object blah = null; var c = new Goo { Gibberish = blah }; } }", index: LocalIndex); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember1() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { Console.[|WriteLine|](); }"); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember2() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { [|WriteLine|](); }"); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember3() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { [|WriteLine|] }"); } [WorkItem(544384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544384")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPointerType() { await TestInRegularAndScriptAsync( @"class Program { static int x; unsafe static void F(int* p) { *p = 1; } static unsafe void Main(string[] args) { int[] a = new int[10]; fixed (int* p2 = &x, int* p3 = ) F(GetP2([|p2|])); } unsafe private static int* GetP2(int* p2) { return p2; } }", @"class Program { static int x; private static unsafe int* p2; unsafe static void F(int* p) { *p = 1; } static unsafe void Main(string[] args) { int[] a = new int[10]; fixed (int* p2 = &x, int* p3 = ) F(GetP2(p2)); } unsafe private static int* GetP2(int* p2) { return p2; } }"); } [WorkItem(544510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544510")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnUsingAlias() { await TestMissingInRegularAndScriptAsync( @"using [|S|] = System ; S . Console . WriteLine ( ""hello world"" ) ; "); } [WorkItem(544907, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExpressionTLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Linq.Expressions; class C { static void Main() { Expression<Func<int, int>> e = x => [|Goo|]; } }", @"using System; using System.Linq.Expressions; class C { public static int Goo { get; private set; } static void Main() { Expression<Func<int, int>> e = x => Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoGenerationIntoEntirelyHiddenType() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { int i = D.[|Bar|]; } } #line hidden class D { } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInReturnStatement() { await TestInRegularAndScriptAsync( @"class Program { void Main() { return [|goo|]; } }", @"class Program { private object goo; void Main() { return goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocal1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { Goo([|bar|]); } static void Goo(int i) { } }", @"class Program { void Main() { int bar = 0; Goo(bar); } static void Goo(int i) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalTopLevelNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Program { void Main() { Goo([|bar|]); } static void Goo(string? s) { } }", @"#nullable enable class Program { void Main() { string? bar = null; Goo(bar); } static void Goo(string? s) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalNestedNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Program { void Main() { Goo([|bar|]); } static void Goo(IEnumerable<string?> s) { } }", @"#nullable enable class Program { void Main() { IEnumerable<string?> bar = null; Goo(bar); } static void Goo(IEnumerable<string?> s) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalMissingForVar() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { var x = [|var|]; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOutLocal1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { Goo(out [|bar|]); } static void Goo(out int i) { } }", @"class Program { void Main() { int bar; Goo(out bar); } static void Goo(out int i) { } }", index: ReadonlyFieldIndex); } [WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalBeforeComment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", @"class Program { void Main() { #if true int local; // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", index: ReadonlyFieldIndex); } [WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalAfterComment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int local; int.TryParse(""123"", out [|local|]); #endif } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoVisiblePortion() { await TestInRegularAndScriptAsync( @"using System; #line hidden class Program { void Main() { #line default Goo(Program.[|X|]) } }", @"using System; #line hidden class Program { void Main() { #line default Goo(Program.X) } public static object X { get; private set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingWhenNoAvailableRegionToGenerateInto() { await TestMissingInRegularAndScriptAsync( @"using System; #line hidden class Program { void Main() { #line default Goo(Program.[|X|]) #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalAvailableIfBlockIsNotHidden() { await TestInRegularAndScriptAsync( @"using System; #line hidden class Program { #line default void Main() { Goo([|x|]); } #line hidden } #line default", @"using System; #line hidden class Program { #line default void Main() { object x = null; Goo(x); } #line hidden } #line default"); } [WorkItem(545217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalNameSimplificationCSharp7() { await TestAsync( @"class Program { void goo() { bar([|xyz|]); } struct sfoo { } void bar(sfoo x) { } }", @"class Program { void goo() { sfoo xyz = default(sfoo); bar(xyz); } struct sfoo { } void bar(sfoo x) { } }", index: 3, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); } [WorkItem(545217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalNameSimplification() { await TestInRegularAndScriptAsync( @"class Program { void goo() { bar([|xyz|]); } struct sfoo { } void bar(sfoo x) { } }", @"class Program { void goo() { sfoo xyz = default; bar(xyz); } struct sfoo { } void bar(sfoo x) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestParenthesizedExpression() { await TestInRegularAndScriptAsync( @"class Program { void Main() { int v = 1 + ([|k|]); } }", @"class Program { private int k; void Main() { int v = 1 + (k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInSelect() { await TestInRegularAndScriptAsync( @"using System.Linq; class Program { void Main(string[] args) { var q = from a in args select [|v|]; } }", @"using System.Linq; class Program { private object v; void Main(string[] args) { var q = from a in args select v; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInChecked() { await TestInRegularAndScriptAsync( @"class Program { void Main() { int[] a = null; int[] temp = checked([|goo|]); } }", @"class Program { private int[] goo; void Main() { int[] a = null; int[] temp = checked(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInArrayRankSpecifier() { await TestInRegularAndScriptAsync( @"class Program { void Main() { var v = new int[[|k|]]; } }", @"class Program { private int k; void Main() { var v = new int[k]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional1() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = [|goo|] ? bar : baz; } }", @"class Program { private static bool goo; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional2() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = goo ? [|bar|] : baz; } }", @"class Program { private static int bar; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional3() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = goo ? bar : [|baz|]; } }", @"class Program { private static int baz; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInCast() { await TestInRegularAndScriptAsync( @"class Program { void Main() { var x = (int)[|y|]; } }", @"class Program { private int y; void Main() { var x = (int)y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInIf() { await TestInRegularAndScriptAsync( @"class Program { void Main() { if ([|goo|]) { } } }", @"class Program { private bool goo; void Main() { if (goo) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInSwitch() { await TestInRegularAndScriptAsync( @"class Program { void Main() { switch ([|goo|]) { } } }", @"class Program { private int goo; void Main() { switch (goo) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnNamespace() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnType() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnBase() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|base|].ToString(); } }"); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = 1; } }", @"class Program { void Main() { var undefined = 1; } }", index: PropertyIndex, options: ImplicitTypingEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFuncAssignment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = (x) => 2; } }", @"class Program { void Main() { System.Func<object, int> undefined = (x) => 2; } }", index: PropertyIndex); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign1NotAsVar() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = 1; } }", @"class Program { void Main() { int undefined = 1; } }", index: PropertyIndex); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign2() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = new { P = ""1"" }; } }", @"class Program { void Main() { var undefined = new { P = ""1"" }; } }", index: PropertyIndex); } [WorkItem(545269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInVenus1() { await TestMissingInRegularAndScriptAsync( @"class C { #line 1 ""goo"" void Goo() { this.[|Bar|] = 1; } #line default #line hidden }"); } [WorkItem(545269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInVenus2() { var code = @" class C { #line 1 ""goo"" void Goo() { [|Bar|] = 1; } #line default #line hidden } "; await TestExactActionSetOfferedAsync(code, new[] { string.Format(FeaturesResources.Generate_local_0, "Bar"), string.Format(FeaturesResources.Generate_parameter_0, "Bar") }); await TestInRegularAndScriptAsync(code, @" class C { #line 1 ""goo"" void Goo() { var [|Bar|] = 1; } #line default #line hidden } ", options: ImplicitTypingEverywhere()); } [WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyFromAttribute() { await TestInRegularAndScriptAsync( @"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [MyAttr(123, [|Value|] = 1)] class D { }", @"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { public int Value { get; set; } } [MyAttr(123, Value = 1)] class D { }"); } [WorkItem(545232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNewLinePreservationBeforeInsertingLocal() { await TestInRegularAndScriptAsync( @"using System; namespace CSharpDemoApp { class Program { static void Main(string[] args) { const int MEGABYTE = 1024 * 1024; Console.WriteLine(MEGABYTE); Calculate([|multiplier|]); } static void Calculate(double multiplier = Math.PI) { } } } ", @"using System; namespace CSharpDemoApp { class Program { static void Main(string[] args) { const int MEGABYTE = 1024 * 1024; Console.WriteLine(MEGABYTE); double multiplier = 0; Calculate(multiplier); } static void Calculate(double multiplier = Math.PI) { } } } ", index: LocalIndex); } [WorkItem(863346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod_Local() { await TestInRegularAndScriptAsync( @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { T t = WrapFunc<T>([|NewLocal|]); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { Func<T1, T> NewLocal = null; T t = WrapFunc<T>(NewLocal); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", index: LocalIndex); } [WorkItem(863346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod_Property() { await TestInRegularAndScriptAsync( @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { T t = WrapFunc<T>([|NewLocal|]); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", @"using System; class TestClass<T1> { public static Func<T1, object> NewLocal { get; private set; } static T TestMethod<T>(T item) { T t = WrapFunc<T>(NewLocal); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } "); } [WorkItem(865067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865067")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInMethod() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { IEnumerable<DayOfWeek> Goo() { yield return [|abc|]; } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; IEnumerable<DayOfWeek> Goo() { yield return abc; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInAsyncMethod() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { async IAsyncEnumerable<DayOfWeek> Goo() { yield return [|abc|]; } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; async IAsyncEnumerable<DayOfWeek> Goo() { yield return abc; } }"); } [WorkItem(30235, "https://github.com/dotnet/roslyn/issues/30235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void M() { IEnumerable<DayOfWeek> F() { yield return [|abc|]; } } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; void M() { IEnumerable<DayOfWeek> F() { yield return abc; } } }"); } [WorkItem(877580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/877580")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithThrow() { await TestInRegularAndScriptAsync( @"using System; class Program { void Goo() { throw [|MyExp|]; } }", @"using System; class Program { private Exception MyExp; void Goo() { throw MyExp; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { private unsafe int* goo; void Method() { int* a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { private unsafe int*[] goo; void Method() { int*[] a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { private int* goo; void Method() { int* a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { private int* goo; void Method() { int* a = goo; } } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { private static unsafe int* goo; unsafe class MyClass { void Method() { int* a = Class.goo; } } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { private readonly unsafe int* goo; void Method() { int* a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { private readonly unsafe int*[] goo; void Method() { int*[] a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { private readonly int* goo; void Method() { int* a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { private readonly int* goo; void Method() { int* a = goo; } } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { private static readonly unsafe int* goo; unsafe class MyClass { void Method() { int* a = Class.goo; } } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeProperty() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { public unsafe int* goo { get; private set; } void Method() { int* a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeProperty2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { public unsafe int*[] goo { get; private set; } void Method() { int*[] a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { public int* goo { get; private set; } void Method() { int* a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { public int* goo { get; private set; } void Method() { int* a = goo; } } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { public static unsafe int* goo { get; private set; } unsafe class MyClass { void Method() { int* a = Class.goo; } } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { private object Z; void M() { var x = nameof(Z); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z.X); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { private object Z; void M() { var x = nameof(Z.X); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z.X); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z.X); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z.X.Y); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { private object Z; void M() { var x = nameof(Z.X.Y); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z.X.Y); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z.X.Y); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var x = [|nameof(1 + 2)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var y = 1 + 2; var x = [|nameof(y)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing3() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var y = 1 + 2; var z = """"; var x = [|nameof(y, z)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { public object y { get; private set; } void M() { var x = nameof(y, z); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { private object y; void M() { var x = nameof(y, z); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { private readonly object y; void M() { var x = nameof(y, z); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { void M() { object y = null; var x = nameof(y, z); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { public object y { get; private set; } void M() { var x = nameof(y); } private object nameof(object y) { return null; } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { private object y; void M() { var x = nameof(y); } private object nameof(object y) { return null; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { private readonly object y; void M() { var x = nameof(y); } private object nameof(object y) { return null; } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { void M() { object y = null; var x = nameof(y); } private object nameof(object y) { return null; } }", index: LocalIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { public C Instance { get; private set; } void Main(C a) { C x = a?.Instance; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { private C Instance; void Main(C a) { C x = a?.Instance; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { private readonly C Instance; void Main(C a) { C x = a?.Instance; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { public object Instance { get; private set; } void Main(C a) { var x = a?.Instance; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { private object Instance; void Main(C a) { var x = a?.Instance; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarReadOnlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { private readonly object Instance; void Main(C a) { var x = a?.Instance; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { public int B { get; private set; } void Main(C a) { int? x = a?.B; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { private int B; void Main(C a) { int? x = a?.B; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { private readonly int B; void Main(C a) { int? x = a?.B; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { public C C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { public int C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { public int C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { public object C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { internal C C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { internal int C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { internal int C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { internal object C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { internal readonly C C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { internal readonly int C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { internal readonly int C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { internal readonly object C; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { private static int y; public int MyProperty { get; } = y; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { private static readonly int y; public int MyProperty { get; } = y; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public static int y { get; private set; } public int MyProperty { get; } = y; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { private int y; public int Y => y; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { private readonly int y; public int Y => y; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { public int Y => y; public int y { get; private set; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { private static C x; public static C operator --(C p) => x; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { private static readonly C x; public static C operator --(C p) => x; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static C operator --(C p) => x; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { private static C x; public static C GetValue(C p) => x; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { private static readonly C x; public static C GetValue(C p) => x; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static C GetValue(C p) => x; }", index: PropertyIndex); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTMethod() { await TestInRegularAndScriptAsync( @"class C { public static async System.Threading.Tasks.Task<C> GetValue(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static async System.Threading.Tasks.Task<C> GetValue(C p) => x; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { private static string key; static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { public static string One { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { private static int i; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { private static readonly string key; static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { private static string One; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { private static readonly int i; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { public static string key { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { private static readonly string One; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { public static int i { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { string key = null; var x = new Dictionary<string, int> { [key] = 0 }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { string One = null; var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { int i = 0; var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { private static Func<int> goo; static void Main(string[] args) { goo = () => { return 0; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda2() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { public static Func<int> goo { get; private set; } static void Main(string[] args) { goo = () => { return 0; }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda3() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { static void Main(string[] args) { Func<int> goo = () => { return 0; }; } }", index: PropertyIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Field() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { private static int _field; public static int Property1 { get { return _field; } } }"); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_ReadonlyField() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { private static readonly int _field; public static int Property1 { get { return _field; } } }", index: ReadonlyFieldIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Property() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { public static int Property1 { get { return _field; } } public static int _field { get; private set; } }", index: PropertyIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Local() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { public static int Property1 { get { int _field = 0; return _field; } } }", index: LocalIndex); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSameNameAsInstanceVariableInContainingType() { await TestInRegularAndScriptAsync( @"class Outer { int _field; class Inner { public Inner(int field) { [|_field|] = field; } } }", @"class Outer { int _field; class Inner { private int _field; public Inner(int field) { _field = field; } } }"); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnStaticWithExistingInstance1() { await TestMissingInRegularAndScriptAsync( @"class C { int _field; void M() { C.[|_field|] = 42; } }"); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnStaticWithExistingInstance2() { await TestMissingInRegularAndScriptAsync( @"class C { int _field; static C() { [|_field|] = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRead() { await TestInRegularAndScriptAsync( @"class Class { void Method((int, string) i) { Method([|tuple|]); } }", @"class Class { private (int, string) tuple; void Method((int, string) i) { Method(tuple); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWithOneNameRead() { await TestInRegularAndScriptAsync( @"class Class { void Method((int a, string) i) { Method([|tuple|]); } }", @"class Class { private (int a, string) tuple; void Method((int a, string) i) { Method(tuple); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWrite() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|tuple|] = (1, ""hello""); } }", @"class Class { private (int, string) tuple; void Method() { tuple = (1, ""hello""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWithOneNameWrite() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|tuple|] = (a: 1, ""hello""); } }", @"class Class { private (int a, string) tuple; void Method() { tuple = (a: 1, ""hello""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRefReturnProperties() { await TestInRegularAndScriptAsync( @" using System; class C { public void Goo() { ref int i = ref this.[|Bar|]; } }", @" using System; class C { public ref int Bar => throw new NotImplementedException(); public void Goo() { ref int i = ref this.Bar; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRefWithField() { await TestInRegularAndScriptAsync( @" using System; class C { public void Goo() { ref int i = ref this.[|bar|]; } }", @" using System; class C { private int bar; public void Goo() { ref int i = ref this.bar; } }"); } [WorkItem(17621, "https://github.com/dotnet/roslyn/issues/17621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithMatchingTypeName1() { await TestInRegularAndScript1Async( @" using System; public class Goo { public Goo(String goo) { [|String|] = goo; } }", @" using System; public class Goo { public Goo(String goo) { String = goo; } public string String { get; } }"); } [WorkItem(17621, "https://github.com/dotnet/roslyn/issues/17621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithMatchingTypeName2() { await TestInRegularAndScript1Async( @" using System; public class Goo { public Goo(String goo) { [|String|] = goo; } }", @" using System; public class Goo { public Goo(String goo) { String = goo; } public string String { get; private set; } }", index: ReadonlyFieldIndex); } [WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestContextualKeyword1() { await TestMissingInRegularAndScriptAsync( @" namespace N { class nameof { } } class C { void M() { [|nameof|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreferReadOnlyIfAfterReadOnlyAssignment() { await TestInRegularAndScriptAsync( @"class Class { private readonly int _goo; public Class() { _goo = 0; [|_bar|] = 1; } }", @"class Class { private readonly int _goo; private readonly int _bar; public Class() { _goo = 0; _bar = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreferReadOnlyIfBeforeReadOnlyAssignment() { await TestInRegularAndScriptAsync( @"class Class { private readonly int _goo; public Class() { [|_bar|] = 1; _goo = 0; } }", @"class Class { private readonly int _bar; private readonly int _goo; public Class() { _bar = 1; _goo = 0; } }"); } [WorkItem(19239, "https://github.com/dotnet/roslyn/issues/19239")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyPropertyInConstructor() { await TestInRegularAndScriptAsync( @"class Class { public Class() { [|Bar|] = 1; } }", @"class Class { public Class() { Bar = 1; } public int Bar { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlaceFieldBasedOnSurroundingStatements() { await TestInRegularAndScriptAsync( @"class Class { private int _goo; private int _quux; public Class() { _goo = 0; [|_bar|] = 1; _quux = 2; } }", @"class Class { private int _goo; private int _bar; private int _quux; public Class() { _goo = 0; _bar = 1; _quux = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlaceFieldBasedOnSurroundingStatements2() { await TestInRegularAndScriptAsync( @"class Class { private int goo; private int quux; public Class() { this.goo = 0; this.[|bar|] = 1; this.quux = 2; } }", @"class Class { private int goo; private int bar; private int quux; public Class() { this.goo = 0; this.bar = 1; this.quux = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlacePropertyBasedOnSurroundingStatements() { await TestInRegularAndScriptAsync( @"class Class { public int Goo { get; } public int Quuz { get; } public Class() { Goo = 0; [|Bar|] = 1; Quux = 2; } }", @"class Class { public int Goo { get; } public int Bar { get; } public int Quuz { get; } public Class() { Goo = 0; Bar = 1; Quux = 2; } }"); } [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnGenericCodeParsedAsExpression() { await TestMissingAsync(@" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 > return ImmutableArray.CreateRange(); } }"); } [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnNonGenericExpressionWithLessThan() { await TestInRegularAndScriptAsync(@" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 return ImmutableArray.CreateRange(); } }", @" class C { public int IEnumerable { get; private set; } private void GetEvaluationRuleNames() { IEnumerable < Int32 return ImmutableArray.CreateRange(); } }"); } [WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task GroupNonReadonlyFieldsTogether() { await TestInRegularAndScriptAsync(@" class C { public bool isDisposed; public readonly int x; public readonly int m; public C() { this.[|y|] = 0; } }", @" class C { public bool isDisposed; private int y; public readonly int x; public readonly int m; public C() { this.y = 0; } }"); } [WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task GroupReadonlyFieldsTogether() { await TestInRegularAndScriptAsync(@" class C { public readonly int x; public readonly int m; public bool isDisposed; public C() { this.[|y|] = 0; } }", @" class C { public readonly int x; public readonly int m; private readonly int y; public bool isDisposed; public C() { this.y = 0; } }", index: ReadonlyFieldIndex); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithOutOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo(out [|goo|]); } void Goo(int i) { } void Goo(out bool b) { } }", @"class Class { private bool goo; void Method() { Goo(out goo); } void Goo(int i) { } void Goo(out bool b) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithOutOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo([|goo|]); } void Goo(out bool b) { } void Goo(int i) { } }", @"class Class { private int goo; void Method() { Goo(goo); } void Goo(out bool b) { } void Goo(int i) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithRefOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo(ref [|goo|]); } void Goo(int i) { } void Goo(ref bool b) { } }", @"class Class { private bool goo; void Method() { Goo(ref goo); } void Goo(int i) { } void Goo(ref bool b) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithRefOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo([|goo|]); } void Goo(ref bool b) { } void Goo(int i) { } }", @"class Class { private int goo; void Method() { Goo(goo); } void Goo(ref bool b) { } void Goo(int i) { } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|_field|]; } }", @"class Program { private int _field; public int Property { get => _field; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedGetterWithDifferentAccessibility() { await TestInRegularAndScriptAsync( @"class Program { public int Property { protected get => [|_field|]; set => throw new System.NotImplementedException(); } }", @"class Program { private int _field; public int Property { protected get => _field; set => throw new System.NotImplementedException(); } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|_readonlyField|]; } }", @"class Program { private readonly int _readonlyField; public int Property { get => _readonlyField; } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|prop|]; } }", @"class Program { public int Property { get => prop; } public int prop { get; private set; } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedSetterInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public int Property { set => [|_field|] = value; } }", @"class Program { private int _field; public int Property { set => _field = value; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_field|]; } }", @"class Program { private int _field; public void Method() { int Local() => _field; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_readonlyField|]; } }", @"class Program { private readonly int _readonlyField; public void Method() { int Local() => _readonlyField; } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|prop|]; } }", @"class Program { public int prop { get; private set; } public void Method() { int Local() => prop; } }", index: PropertyIndex); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { async System.Threading.Tasks.Task<int> Local() => [|prop|]; } }", @"class Program { public int prop { get; private set; } public void Method() { async System.Threading.Tasks.Task<int> Local() => prop; } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_field|] = 12; } }", @"class Program { private int _field; public void Method() { int Local() => _field = 12; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_field|]; } } }", @"class Program { private int _field; public void Method() { int Local() { return _field; } } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_readonlyField|]; } } }", @"class Program { private readonly int _readonlyField; public void Method() { int Local() { return _readonlyField; } } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|prop|]; } } }", @"class Program { public int prop { get; private set; } public void Method() { int Local() { return prop; } } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInBlockBodiedAsyncTaskOfTLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { async System.Threading.Tasks.Task<int> Local() { return [|prop|]; } } }", @"class Program { public int prop { get; private set; } public void Method() { async System.Threading.Tasks.Task<int> Local() { return prop; } } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunctionInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_field|] = 12; } } }", @"class Program { private int _field; public void Method() { int Local() { return _field = 12; } } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunctionInsideLambdaExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { public void Method() { Action action = () => { int Local() { return [|_field|]; } }; } }", @" using System; class Program { private int _field; public void Method() { Action action = () => { int Local() { return _field; } }; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInsideLambdaExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { public void Method() { Action action = () => { int Local() => [|_field|]; }; } }", @" using System; class Program { private int _field; public void Method() { Action action = () => { int Local() => _field; }; } }"); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { private object goo; void Method() { lock (goo) { } } }"); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { private readonly object goo; void Method() { lock (goo) { } } }", index: 1); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { public object goo { get; private set; } void Method() { lock (goo) { } } }", index: 2); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: int i }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: int i }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern2() { await TestInRegularAndScriptAsync( @" class C { void M2() { Blah o = null; if (o is { [|X|]: int i }) { } } class Blah { } }", @" class C { void M2() { Blah o = null; if (o is { X: int i }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern3() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { X: { [|Y|]: int i } }) { } } class Frob { } class Blah { public Frob X; } }", @" class C { void M2() { object o = null; if (o is Blah { X: { Y: int i } }) { } } class Frob { public int Y { get; internal set; } } class Blah { public Frob X; } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern4() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: }) { } } class Blah { public object X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern5() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: Frob { } }) { } } class Blah { } class Frob { } }", @" class C { void M2() { object o = null; if (o is Blah { X: Frob { } }) { } } class Blah { public Frob X { get; internal set; } } class Frob { } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern6() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (1, 2) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (1, 2) }) { } } class Blah { public (int, int) X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern7() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (y: 1, z: 2) }) { } } class Blah { } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, @" class C { void M2() { object o = null; if (o is Blah { X: (y: 1, z: 2) }) { } } class Blah { public (int y, int z) X { get; internal set; } } } " + TestResources.NetFX.ValueTuple.tuplelib_cs); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern8() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: () }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: () }) { } } class Blah { public object X { get; internal set; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExtendedPropertyPatternInIsPattern() { await TestInRegularAndScriptAsync( @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah.[|X|]: (y: 1, z: 2) }) { } } class Blah { } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah.X: (y: 1, z: 2) }) { } } class Blah { public (int y, int z) X { get; internal set; } } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantPatternInPropertyPattern() { await TestInRegularAndScriptAsync( @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah: [|MissingConstant|] }) { } } class Blah { } } ", @" class C { private const Blah MissingConstant; Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah: MissingConstant }) { } } class Blah { } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantPatternInExtendedPropertyPattern() { await TestInRegularAndScriptAsync( @" class C { C SomeC { get; set; } Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeC.SomeBlah: [|MissingConstant|] }) { } } class Blah { } } ", @" class C { private const Blah MissingConstant; C SomeC { get; set; } Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeC.SomeBlah: MissingConstant }) { } } class Blah { } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern9() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (1) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (1) }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern10() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (y: 1) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (y: 1) }) { } } class Blah { public object X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPatternWithNullablePattern() { await TestInRegularAndScriptAsync( @"#nullable enable class C { void M2() { object? o = null; object? zToMatch = null; if (o is Blah { [|X|]: (y: 1, z: zToMatch) }) { } } class Blah { } }", @"#nullable enable class C { void M2() { object? o = null; object? zToMatch = null; if (o is Blah { X: (y: 1, z: zToMatch) }) { } } class Blah { public (int y, object? z) X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInCasePattern1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; switch (o) { case Blah { [|X|]: int i }: break; } } class Blah { } }", @" class C { void M2() { object o = null; switch (o) { case Blah { X: int i }: break; } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInCasePattern2() { await TestInRegularAndScriptAsync( @" class C { void M2() { Blah o = null; switch (o) { case { [|X|]: int i }: break; } } class Blah { } }", @" class C { void M2() { Blah o = null; switch (o) { case { X: int i }: break; } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsSwitchExpression1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; _ = o switch { Blah { [|X|]: int i } => 0, _ => 0 }; } class Blah { } }", @" class C { void M2() { object o = null; _ = o switch { Blah { X: int i } => 0, _ => 0 }; } class Blah { public int X { get; internal set; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternGenerateConstant() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; _ = o switch { Blah { X: [|Y|] } => 0, _ => 0 }; } class Blah { public int X; } }", @" class C { private const int Y; void M2() { object o = null; _ = o switch { Blah { X: Y } => 0, _ => 0 }; } class Blah { public int X; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameter() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { void Method(object goo) { goo; } }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameter_DoesntAddToInterface() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class { public void Method() { [|goo|]; } }", @"interface Interface { void Method(); } class Class { public void Method(object goo) { [|goo|]; } }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterAndOverrides_AddsToInterface() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class : Interface { public void Method() { [|goo|]; } }", @"interface Interface { void Method(object goo); } class Class : Interface { public void Method(object goo) { [|goo|]; } }", index: ParameterAndOverrides); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterIsOfCorrectType() { await TestInRegularAndScriptAsync( @"class Class { void Method() { M1([|goo|]); } void M1(int a); }", @"class Class { void Method(int goo) { M1(goo); } void M1(int a); }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterAndOverrides_IsOfCorrectType() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class : Interface { public void Method() { M1([|goo|]); } void M1(int a); }", @"interface Interface { void Method(int goo); } class Class : Interface { public void Method(int goo) { M1(goo); } void M1(int a); }", index: ParameterAndOverrides); } [WorkItem(26502, "https://github.com/dotnet/roslyn/issues/26502")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoReadOnlyMembersWhenInLambdaInConstructor() { await TestExactActionSetOfferedAsync( @"using System; class C { public C() { Action a = () => { this.[|Field|] = 1; }; } }", new[] { string.Format(FeaturesResources.Generate_property_1_0, "Field", "C"), string.Format(FeaturesResources.Generate_field_1_0, "Field", "C"), }); } [WorkItem(26502, "https://github.com/dotnet/roslyn/issues/26502")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoReadOnlyMembersWhenInLocalFunctionInConstructor() { await TestExactActionSetOfferedAsync( @"using System; class C { public C() { void Goo() { this.[|Field|] = 1; }; } }", new[] { string.Format(FeaturesResources.Generate_property_1_0, "Field", "C"), string.Format(FeaturesResources.Generate_field_1_0, "Field", "C"), }); } [WorkItem(45367, "https://github.com/dotnet/roslyn/issues/45367")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontOfferPropertyOrFieldInNamespace() { await TestExactActionSetOfferedAsync( @"using System; namespace ConsoleApp5 { class MyException: Exception internal MyException(int error, int offset, string message) : base(message) { [|Error|] = error; Offset = offset; }", new[] { string.Format(FeaturesResources.Generate_local_0, "Error", "MyException"), string.Format(FeaturesResources.Generate_parameter_0, "Error", "MyException"), }); } [WorkItem(48172, "https://github.com/dotnet/roslyn/issues/48172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOfferParameterInTopLevel() { await TestMissingAsync("[|Console|].WriteLine();", new TestParameters(Options.Regular)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.GenerateVariable; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateVariable { public class GenerateVariableTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { private const int FieldIndex = 0; private const int ReadonlyFieldIndex = 1; private const int PropertyIndex = 2; private const int LocalIndex = 3; private const int Parameter = 4; private const int ParameterAndOverrides = 5; public GenerateVariableTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer?, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpGenerateVariableCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); // specify all options explicitly to override defaults. private OptionsCollection ImplicitTypingEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleLowercaseIdentifier1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { private object goo; void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleLowercaseIdentifier2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { private readonly object goo; void Method() { goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestTestSimpleLowercaseIdentifier3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { public object goo { get; private set; } void Method() { goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { public object Goo { get; private set; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { private object Goo; void Method() { Goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleUppercaseIdentifier3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } }", @"class Class { private readonly object Goo; void Method() { Goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleRead1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { Method([|goo|]); } }", @"class Class { private int goo; void Method(int i) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleReadWithTopLevelNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Class { void Method(string? s) { Method([|goo|]); } }", @"#nullable enable class Class { private string? goo; void Method(string? s) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleReadWithNestedNullability() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Collections.Generic; class Class { void Method(IEnumerable<string?> s) { Method([|goo|]); } }", @"#nullable enable using System.Collections.Generic; class Class { private IEnumerable<string?> goo; void Method(IEnumerable<string?> s) { Method(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWriteCount() { await TestExactActionSetOfferedAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_property_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWriteInOverrideCount() { await TestExactActionSetOfferedAsync( @" abstract class Base { public abstract void Method(int i); } class Class : Base { public override void Method(int i) { [|goo|] = 1; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_property_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0_and_overrides_implementations, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWrite1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", @"class Class { private int goo; void Method(int i) { goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSimpleWrite2() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = 1; } }", @"class Class { public int goo { get; private set; } void Method(int i) { goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInRef() { await TestInRegularAndScriptAsync( @"class Class { void Method(ref int i) { Method(ref this.[|goo|]); } }", @"class Class { private int goo; void Method(ref int i) { Method(ref this.[|goo|]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInRef() { await TestInRegularAndScriptAsync( @" using System; class Class { void Method(ref int i) { Method(ref this.[|goo|]); } }", @" using System; class Class { public ref int goo => throw new NotImplementedException(); void Method(ref int i) { Method(ref this.goo); } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInIn() { await TestInRegularAndScriptAsync( @" using System; class Class { void Method(in int i) { Method(in this.[|goo|]); } }", @" using System; class Class { public ref readonly int goo => throw new NotImplementedException(); void Method(in int i) { Method(in this.goo); } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInRef1() { await TestInRegularAndScriptAsync( @"class Class { void Method(ref int i) { Method(ref [|goo|]); } }", @"class Class { private int goo; void Method(ref int i) { Method(ref goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInOutCodeActionCount() { await TestExactActionSetOfferedAsync( @"class Class { void Method(out int i) { Method(out [|goo|]); } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "goo", "Class"), string.Format(FeaturesResources.Generate_local_0, "goo"), string.Format(FeaturesResources.Generate_parameter_0, "goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInOut1() { await TestInRegularAndScriptAsync( @"class Class { void Method(out int i) { Method(out [|goo|]); } }", @"class Class { private int goo; void Method(out int i) { Method(out goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember1() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { private static object goo; static void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember2() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { private static readonly object goo; static void Method() { goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInStaticMember3() { await TestInRegularAndScriptAsync( @"class Class { static void Method() { [|goo|]; } }", @"class Class { public static object goo { get; private set; } static void Method() { goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { private object goo; void Method() { this.goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { private readonly object goo; void Method() { this.goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffInstance3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|]; } }", @"class Class { public object goo { get; private set; } void Method() { this.goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenInstance1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|] = 1; } }", @"class Class { private int goo; void Method() { this.goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenInstance2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { this.[|goo|] = 1; } }", @"class Class { public int goo { get; private set; } void Method() { this.goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { private static object goo; void Method() { Class.goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { private static readonly object goo; void Method() { Class.goo; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffStatic3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|]; } }", @"class Class { public static object goo { get; private set; } void Method() { Class.goo; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenStatic1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|] = 1; } }", @"class Class { private static int goo; void Method() { Class.goo = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateOffWrittenStatic2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Class.[|goo|] = 1; } }", @"class Class { public static int goo { get; private set; } void Method() { Class.goo = 1; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoSibling1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { new D().[|goo|]; } } class D { }", @"class Class { void Method() { new D().goo; } } class D { internal object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoOuter1() { await TestInRegularAndScriptAsync( @"class Outer { class Class { void Method() { new Outer().[|goo|]; } } }", @"class Outer { private object goo; class Class { void Method() { new Outer().goo; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInstanceIntoDerived1() { await TestInRegularAndScriptAsync( @"class Class : Base { void Method(Base b) { b.[|goo|]; } } class Base { }", @"class Class : Base { void Method(Base b) { b.goo; } } class Base { internal object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateStaticIntoDerived1() { await TestInRegularAndScriptAsync( @"class Class : Base { void Method(Base b) { Base.[|goo|]; } } class Base { }", @"class Class : Base { void Method(Base b) { Base.goo; } } class Base { protected static object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterfaceFixCount() { await TestActionCountAsync( @"class Class { void Method(I i) { i.[|goo|]; } } interface I { }", count: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterface1() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|]; } } interface I { }", @"class Class { void Method(I i) { i.Goo; } } interface I { object Goo { get; set; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoInterface2() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|]; } } interface I { }", @"class Class { void Method(I i) { i.Goo; } } interface I { object Goo { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateStaticIntoInterfaceMissing() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method(I i) { I.[|Goo|]; } } interface I { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateWriteIntoInterfaceFixCount() { await TestActionCountAsync( @"class Class { void Method(I i) { i.[|Goo|] = 1; } } interface I { }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateWriteIntoInterface1() { await TestInRegularAndScriptAsync( @"class Class { void Method(I i) { i.[|Goo|] = 1; } } interface I { }", @"class Class { void Method(I i) { i.Goo = 1; } } interface I { int Goo { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericType() { await TestInRegularAndScriptAsync( @"class Class<T> { void Method(T t) { [|goo|] = t; } }", @"class Class<T> { private T goo; void Method(T t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod1() { await TestInRegularAndScriptAsync( @"class Class { void Method<T>(T t) { [|goo|] = t; } }", @"class Class { private object goo; void Method<T>(T t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod2() { await TestInRegularAndScriptAsync( @"class Class { void Method<T>(IList<T> t) { [|goo|] = t; } }", @"class Class { private IList<object> goo; void Method<T>(IList<T> t) { goo = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldBeforeFirstField() { await TestInRegularAndScriptAsync( @"class Class { int i; void Method() { [|goo|]; } }", @"class Class { int i; private object goo; void Method() { goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldAfterLastField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } int i; }", @"class Class { void Method() { goo; } int i; private object goo; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastField1() { await TestInRegularAndScriptAsync( @"class Class { int Bar; void Method() { [|Goo|]; } }", @"class Class { int Bar; public object Goo { get; private set; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|]; } int Bar; }", @"class Class { void Method() { Goo; } int Bar; public object Goo { get; private set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyBeforeFirstProperty() { await TestInRegularAndScriptAsync( @"class Class { int Quux { get; } void Method() { [|Goo|]; } }", @"class Class { public object Goo { get; private set; } int Quux { get; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyBeforeFirstPropertyEvenWithField1() { await TestInRegularAndScriptAsync( @"class Class { int Bar; int Quux { get; } void Method() { [|Goo|]; } }", @"class Class { int Bar; public object Goo { get; private set; } int Quux { get; } void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyAfterLastPropertyEvenWithField2() { await TestInRegularAndScriptAsync( @"class Class { int Quux { get; } int Bar; void Method() { [|Goo|]; } }", @"class Class { int Quux { get; } public object Goo { get; private set; } int Bar; void Method() { Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInInvocation() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInObjectCreation() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { new [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInTypeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|].B a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.[|B|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B.C|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A.B|].C a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.B.[|C|] a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { [|A|].B.C a; } }"); await TestMissingInRegularAndScriptAsync( @"class Class { void Method() { A.[|B|].C a; } }"); } [WorkItem(539336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingInAttribute() { await TestMissingInRegularAndScriptAsync( @"[[|A|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A|].B] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.[|B|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B.C|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A.B|].C] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.B.[|C|]] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[[|A|].B.C] class Class { }"); await TestMissingInRegularAndScriptAsync( @"[A.B.[|C|]] class Class { }"); } [WorkItem(539340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539340")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSpansField() { await TestSpansAsync( @"class C { void M() { this.[|Goo|] }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|]; }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 + 2 }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] = 1 + 2; }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] += Bar() }"); await TestSpansAsync( @"class C { void M() { this.[|Goo|] += Bar(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInSimpleLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<string, int> f = x => [|goo|]; } }", @"using System; class Program { private static int goo; static void Main(string[] args) { Func<string, int> f = x => goo; } }", FieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInParenthesizedLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int> f = () => [|goo|]; } }", @"using System; class Program { private static int goo; static void Main(string[] args) { Func<int> f = () => goo; } }", FieldIndex); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInAsyncTaskOfTSimpleLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task<int>> f = async x => [|goo|]; } }", @"using System; using System.Threading.Tasks; class Program { private static int goo; static void Main(string[] args) { Func<string, Task<int>> f = async x => goo; } }", FieldIndex); } [WorkItem(30232, "https://github.com/dotnet/roslyn/issues/30232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInAsyncTaskOfTParenthesizedLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<Task<int>> f = async () => [|goo|]; } }", @"using System; using System.Threading.Tasks; class Program { private static int goo; static void Main(string[] args) { Func<Task<int>> f = async () => goo; } }", FieldIndex); } [WorkItem(539427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539427")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromLambda() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { [|goo|] = () => { return 2 }; } }", @"using System; class Class { private Func<int> goo; void Method(int i) { goo = () => { return 2 }; } }"); } // TODO: Move to TypeInferrer.InferTypes, or something [WorkItem(539466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInMethodOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { System.Console.WriteLine([|goo|]); } }", @"class Class { private bool goo; void Method(int i) { System.Console.WriteLine(goo); } }"); } // TODO: Move to TypeInferrer.InferTypes, or something [WorkItem(539466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539466")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInMethodOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method(int i) { System.Console.WriteLine(this.[|goo|]); } }", @"class Class { private bool goo; void Method(int i) { System.Console.WriteLine(this.goo); } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty1() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { get; set; } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { get; set; } } interface ITest { bool SomeProp { get; set; } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty2() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { } } interface ITest { bool SomeProp { get; set; } }", index: ReadonlyFieldIndex); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty3() { await TestInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { }", @"class Class : ITest { bool ITest.SomeProp { } } interface ITest { bool SomeProp { get; } }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty4() { await TestMissingInRegularAndScriptAsync( @"class Class { bool ITest.[|SomeProp|] { } } interface ITest { }"); } [WorkItem(539468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539468")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExplicitProperty5() { await TestMissingInRegularAndScriptAsync( @"class Class : ITest { bool ITest.[|SomeProp|] { } } interface ITest { bool SomeProp { get; } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEscapedName() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|@goo|]; } }", @"class Class { private object goo; void Method() { @goo; } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEscapedKeyword() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|@int|]; } }", @"class Class { private object @int; void Method() { @int; } }"); } [WorkItem(539529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539529")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestRefLambda() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|test|] = (ref int x) => x = 10; } }", @"class Class { private object test; void Method() { test = (ref int x) => x = 10; } }"); } [WorkItem(539595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539595")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnError() { await TestMissingInRegularAndScriptAsync( @"class Class { void F<U, V>(U u1, V v1) { Goo<string, int>([|u1|], u2); } }"); } [WorkItem(539571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539571")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNameSimplification() { await TestInRegularAndScriptAsync( @"namespace TestNs { class Program { class Test { void Meth() { Program.[|blah|] = new Test(); } } } }", @"namespace TestNs { class Program { private static Test blah; class Test { void Meth() { Program.blah = new Test(); } } } }"); } [WorkItem(539717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPostIncrement() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|i|]++; } }", @"class Program { private static int i; static void Main(string[] args) { i++; } }"); } [WorkItem(539717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539717")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreDecrement() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { --[|i|]; } }", @"class Program { private static int i; static void Main(string[] args) { --i; } }"); } [WorkItem(539738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539738")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoScript() { await TestAsync( @"using C; static class C { } C.[|i|] ++ ;", @"using C; static class C { internal static int i; } C.i ++ ;", parseOptions: Options.Script); } [WorkItem(539558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539558")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5565() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|Goo|]#(); } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { public static object Goo { get; private set; } static void Main(string[] args) { Goo#(); } }"); } [WorkItem(539536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539536")] [Fact(Skip = "Tuples"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5538() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { new([|goo|])(); } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { public static object goo { get; private set; } static void Main(string[] args) { new(goo)(); } }", index: PropertyIndex); } [WorkItem(539665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task BugFix5697() { await TestInRegularAndScriptAsync( @"class C { } class D { void M() { C.[|P|] = 10; } } ", @"class C { public static int P { get; internal set; } } class D { void M() { C.P = 10; } } "); } [WorkItem(539793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIncrement() { await TestExactActionSetOfferedAsync( @"class Program { static void Main() { [|p|]++; } }", new[] { string.Format(FeaturesResources.Generate_field_1_0, "p", "Program"), string.Format(FeaturesResources.Generate_property_1_0, "p", "Program"), string.Format(FeaturesResources.Generate_local_0, "p"), string.Format(FeaturesResources.Generate_parameter_0, "p") }); await TestInRegularAndScriptAsync( @"class Program { static void Main() { [|p|]++; } }", @"class Program { private static int p; static void Main() { p++; } }"); } [WorkItem(539834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539834")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task TestNotInGoto() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { goto [|goo|]; } }"); } [WorkItem(539826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539826")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnLeftOfDot() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { [|goo|].ToString(); } }", @"class Program { private static object goo; static void Main() { goo.ToString(); } }"); } [WorkItem(539840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotBeforeAlias() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|global|]::System.String s; } }"); } [WorkItem(539871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539871")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnGenericName() { await TestMissingInRegularAndScriptAsync( @"class C<T> { public delegate void Goo<R>(R r); static void M() { Goo<T> r = [|Goo<T>|]; } }"); } [WorkItem(539934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539934")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnDelegateAddition() { await TestAsync( @"class C { delegate void D(); void M() { D d = [|M1|] + M2; } }", @"class C { private D M1 { get; set; } delegate void D(); void M() { D d = M1 + M2; } }", parseOptions: null); } [WorkItem(539986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestReferenceTypeParameter1() { await TestInRegularAndScriptAsync( @"class C<T> { public void Test() { C<T> c = A.[|M|]; } } class A { }", @"class C<T> { public void Test() { C<T> c = A.M; } } class A { public static C<object> M { get; internal set; } }"); } [WorkItem(539986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestReferenceTypeParameter2() { await TestInRegularAndScriptAsync( @"class C<T> { public void Test() { C<T> c = A.[|M|]; } class A { } }", @"class C<T> { public void Test() { C<T> c = A.M; } class A { public static C<T> M { get; internal set; } } }"); } [WorkItem(540159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540159")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestEmptyIdentifierName() { await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int i = [|@|] } }"); await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int i = [|@|]} }"); } [WorkItem(541194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541194")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestForeachVar() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var v in [|list|]) { } } }", @"using System.Collections.Generic; class C { private IEnumerable<object> list; void M() { foreach (var v in list) { } } }"); } [WorkItem(541265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExtensionMethodUsedAsInstance() { await TestAsync( @"using System; class C { public static void Main() { string s = ""Hello""; [|f|] = s.ExtensionMethod; } } public static class MyExtension { public static int ExtensionMethod(this String s) { return s.Length; } }", @"using System; class C { private static Func<int> f; public static void Main() { string s = ""Hello""; f = s.ExtensionMethod; } } public static class MyExtension { public static int ExtensionMethod(this String s) { return s.Length; } }", parseOptions: null); } [WorkItem(541549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541549")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestDelegateInvoke() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int, int> f = x => x + 1; f([|x|]); } }", @"using System; class Program { private static int x; static void Main(string[] args) { Func<int, int> f = x => x + 1; f(x); } }"); } [WorkItem(541597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestComplexAssign1() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|a|] = a + 10; } }", @"class Program { private static int a; static void Main(string[] args) { a = a + 10; } }"); } [WorkItem(541597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541597")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestComplexAssign2() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { a = [|a|] + 10; } }", @"class Program { private static int a; static void Main(string[] args) { a = a + 10; } }"); } [WorkItem(541659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541659")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestTypeNamedVar() { await TestInRegularAndScriptAsync( @"using System; class Program { public static void Main() { var v = [|p|]; } } class var { }", @"using System; class Program { private static var p; public static void Main() { var v = p; } } class var { }"); } [WorkItem(541675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestStaticExtensionMethodArgument() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { MyExtension.ExMethod([|ss|]); } } static class MyExtension { public static int ExMethod(this string s) { return s.Length; } }", @"using System; class Program { private static string ss; static void Main(string[] args) { MyExtension.ExMethod(ss); } } static class MyExtension { public static int ExMethod(this string s) { return s.Length; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task SpeakableTopLevelStatementType() { await TestMissingAsync(@" [|P|] = 10; partial class Program { }"); } [WorkItem(539675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBeforeCommentBetweenMembers1() { await TestInRegularAndScriptAsync( @"class Program { //method static void Main(string[] args) { [|P|] = 10; } }", @"class Program { public static int P { get; private set; } //method static void Main(string[] args) { P = 10; } }"); } [WorkItem(539675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBeforeCommentBetweenMembers2() { await TestInRegularAndScriptAsync( @"class Program { //method static void Main(string[] args) { [|P|] = 10; } }", @"class Program { private static int P; //method static void Main(string[] args) { P = 10; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBetweenMembers1() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|P|] = 10; } }", @"class Program { private static int P; static void Main(string[] args) { P = 10; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task AddBlankLineBetweenMembers2() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { [|P|] = 10; } }", @"class Program { public static int P { get; private set; } static void Main(string[] args) { P = 10; } }", index: 0); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontAddBlankLineBetweenFields() { await TestInRegularAndScriptAsync( @"class Program { private static int P; static void Main(string[] args) { P = 10; [|A|] = 9; } }", @"class Program { private static int P; private static int A; static void Main(string[] args) { P = 10; A = 9; } }", index: ReadonlyFieldIndex); } [WorkItem(543813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543813")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontAddBlankLineBetweenAutoProperties() { await TestInRegularAndScriptAsync( @"class Program { public static int P { get; private set; } static void Main(string[] args) { P = 10; [|A|] = 9; } }", @"class Program { public static int P { get; private set; } public static int A { get; private set; } static void Main(string[] args) { P = 10; A = 9; } }", index: 0); } [WorkItem(539665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIntoEmptyClass() { await TestInRegularAndScriptAsync( @"class C { } class D { void M() { C.[|P|] = 10; } }", @"class C { public static int P { get; internal set; } } class D { void M() { C.P = 10; } }"); } [WorkItem(540595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540595")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInScript() { await TestAsync( @"[|Goo|]", @"object Goo { get; private set; } Goo", parseOptions: Options.Script); } [WorkItem(542535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542535")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantInParameterValue() { const string Initial = @"class C { const int y = 1 ; public void Goo ( bool x = [|undeclared|] ) { } } "; await TestActionCountAsync( Initial, count: 1); await TestInRegularAndScriptAsync( Initial, @"class C { const int y = 1 ; private const bool undeclared; public void Goo ( bool x = undeclared ) { } } "); } [WorkItem(542900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAttributeNamedArgument1() { await TestInRegularAndScriptAsync( @"using System; class ProgramAttribute : Attribute { [Program([|Name|] = 0)] static void Main(string[] args) { } }", @"using System; class ProgramAttribute : Attribute { public int Name { get; set; } [Program(Name = 0)] static void Main(string[] args) { } }"); } [WorkItem(542900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542900")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAttributeNamedArgument2() { await TestInRegularAndScriptAsync( @"using System; class ProgramAttribute : Attribute { [Program([|Name|] = 0)] static void Main(string[] args) { } }", @"using System; class ProgramAttribute : Attribute { public int Name; [Program(Name = 0)] static void Main(string[] args) { } }", index: ReadonlyFieldIndex); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility1_InternalPrivate() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } private class C { } }", @"class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility2_InternalProtected() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } protected class C { } }", @"class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility3_InternalInternal() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } internal class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility4_InternalProtectedInternal() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } protected internal class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility5_InternalPublic() { await TestAsync( @"class Program { public static void Main() { C c = [|P|]; } public class C { } }", @"class Program { public static C P { get; private set; } public static void Main() { C c = P; } public class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility6_PublicInternal() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } internal class C { } }", @"public class Program { internal static C P { get; private set; } public static void Main() { C c = P; } internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility7_PublicProtectedInternal() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } protected internal class C { } }", @"public class Program { protected internal static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility8_PublicProtected() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } protected class C { } }", @"public class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility9_PublicPrivate() { await TestAsync( @"public class Program { public static void Main() { C c = [|P|]; } private class C { } }", @"public class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility10_PrivatePrivate() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } private class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } private class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility11_PrivateProtected() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } protected class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility12_PrivateProtectedInternal() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } protected internal class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } protected internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility13_PrivateInternal() { await TestAsync( @"class outer { private class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { private class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility14_ProtectedPrivate() { await TestAsync( @"class outer { protected class Program { public static void Main() { C c = [|P|]; } private class C { } } }", @"class outer { protected class Program { private static C P { get; set; } public static void Main() { C c = P; } private class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility15_ProtectedInternal() { await TestAsync( @"class outer { protected class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { protected class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility16_ProtectedInternalProtected() { await TestAsync( @"class outer { protected internal class Program { public static void Main() { C c = [|P|]; } protected class C { } } }", @"class outer { protected internal class Program { protected static C P { get; private set; } public static void Main() { C c = P; } protected class C { } } }", parseOptions: null); } [WorkItem(541698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMinimalAccessibility17_ProtectedInternalInternal() { await TestAsync( @"class outer { protected internal class Program { public static void Main() { C c = [|P|]; } internal class C { } } }", @"class outer { protected internal class Program { public static C P { get; private set; } public static void Main() { C c = P; } internal class C { } } }", parseOptions: null); } [WorkItem(543153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543153")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAnonymousObjectInitializer1() { await TestInRegularAndScriptAsync( @"class C { void M() { var a = new { x = 5 }; a = new { x = [|HERE|] }; } }", @"class C { private int HERE; void M() { var a = new { x = 5 }; a = new { x = HERE }; } }", index: ReadonlyFieldIndex); } [WorkItem(543124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543124")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoGenerationIntoAnonymousType() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { var v = new { }; bool b = v.[|Bar|]; } }"); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOfferedForBoundParametersOfOperators() { await TestMissingInRegularAndScriptAsync( @"class Program { public Program(string s) { } static void Main(string[] args) { Program p = """"; } public static implicit operator Program(string str) { return new Program([|str|]); } }"); } [WorkItem(544175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544175")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnNamedParameterName1() { await TestMissingInRegularAndScriptAsync( @"using System; class class1 { public void Test() { Goo([|x|]: x); } public string Goo(int x) { } }"); } [WorkItem(544271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544271")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnNamedParameterName2() { await TestMissingInRegularAndScriptAsync( @"class Goo { public Goo(int a = 42) { } } class DogBed : Goo { public DogBed(int b) : base([|a|]: b) { } }"); } [WorkItem(544164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544164")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = 24 }; } }", @"class Goo { public int Gibberish { get; internal set; } } class Bar { void goo() { var c = new Goo { Gibberish = 24 }; } }"); } [WorkItem(49294, "https://github.com/dotnet/roslyn/issues/49294")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyInWithInitializer() { await TestInRegularAndScriptAsync( @"record Goo { } class Bar { void goo(Goo g) { var c = g with { [|Gibberish|] = 24 }; } }", @"record Goo { public int Gibberish { get; internal set; } } class Bar { void goo(Goo g) { var c = g with { Gibberish = 24 }; } }"); } [WorkItem(13166, "https://github.com/dotnet/roslyn/issues/13166")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnNestedObjectInitializer() { await TestInRegularAndScriptAsync( @"public class Inner { } public class Outer { public Inner Inner { get; set; } = new Inner(); public static Outer X() => new Outer { Inner = { [|InnerValue|] = 5 } }; }", @"public class Inner { public int InnerValue { get; internal set; } } public class Outer { public Inner Inner { get; set; } = new Inner(); public static Outer X() => new Outer { Inner = { InnerValue = 5 } }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer1() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = Gibberish }; } }", @"class Goo { public object Gibberish { get; internal set; } } class Bar { void goo() { var c = new Goo { Gibberish = Gibberish }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyOnObjectInitializer2() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|Gibberish|] }; } }", @"class Goo { } class Bar { public object Gibberish { get; private set; } void goo() { var c = new Goo { Gibberish = Gibberish }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = 24 }; } }", @"class Goo { internal int Gibberish; } class Bar { void goo() { var c = new Goo { Gibberish = 24 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer1() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { [|Gibberish|] = Gibberish }; } }", @"class Goo { internal object Gibberish; } class Bar { void goo() { var c = new Goo { Gibberish = Gibberish }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFieldOnObjectInitializer2() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|Gibberish|] }; } }", @"class Goo { } class Bar { private object Gibberish; void goo() { var c = new Goo { Gibberish = Gibberish }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnlyPropertyAndFieldOfferedForObjectInitializer() { await TestActionCountAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { . [|Gibberish|] = 24 }; } }", 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInObjectInitializerValue() { await TestInRegularAndScriptAsync( @"class Goo { } class Bar { void goo() { var c = new Goo { Gibberish = [|blah|] }; } }", @"class Goo { } class Bar { void goo() { object blah = null; var c = new Goo { Gibberish = blah }; } }", index: LocalIndex); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember1() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { Console.[|WriteLine|](); }"); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember2() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { [|WriteLine|](); }"); } [WorkItem(544319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnIncompleteMember3() { await TestMissingInRegularAndScriptAsync( @"using System; class Class1 { [|WriteLine|] }"); } [WorkItem(544384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544384")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPointerType() { await TestInRegularAndScriptAsync( @"class Program { static int x; unsafe static void F(int* p) { *p = 1; } static unsafe void Main(string[] args) { int[] a = new int[10]; fixed (int* p2 = &x, int* p3 = ) F(GetP2([|p2|])); } unsafe private static int* GetP2(int* p2) { return p2; } }", @"class Program { static int x; private static unsafe int* p2; unsafe static void F(int* p) { *p = 1; } static unsafe void Main(string[] args) { int[] a = new int[10]; fixed (int* p2 = &x, int* p3 = ) F(GetP2(p2)); } unsafe private static int* GetP2(int* p2) { return p2; } }"); } [WorkItem(544510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544510")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnUsingAlias() { await TestMissingInRegularAndScriptAsync( @"using [|S|] = System ; S . Console . WriteLine ( ""hello world"" ) ; "); } [WorkItem(544907, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExpressionTLambda() { await TestInRegularAndScriptAsync( @"using System; using System.Linq.Expressions; class C { static void Main() { Expression<Func<int, int>> e = x => [|Goo|]; } }", @"using System; using System.Linq.Expressions; class C { public static int Goo { get; private set; } static void Main() { Expression<Func<int, int>> e = x => Goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoGenerationIntoEntirelyHiddenType() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { int i = D.[|Bar|]; } } #line hidden class D { } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInReturnStatement() { await TestInRegularAndScriptAsync( @"class Program { void Main() { return [|goo|]; } }", @"class Program { private object goo; void Main() { return goo; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocal1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { Goo([|bar|]); } static void Goo(int i) { } }", @"class Program { void Main() { int bar = 0; Goo(bar); } static void Goo(int i) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalTopLevelNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Program { void Main() { Goo([|bar|]); } static void Goo(string? s) { } }", @"#nullable enable class Program { void Main() { string? bar = null; Goo(bar); } static void Goo(string? s) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalNestedNullability() { await TestInRegularAndScriptAsync( @"#nullable enable class Program { void Main() { Goo([|bar|]); } static void Goo(IEnumerable<string?> s) { } }", @"#nullable enable class Program { void Main() { IEnumerable<string?> bar = null; Goo(bar); } static void Goo(IEnumerable<string?> s) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalMissingForVar() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { var x = [|var|]; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOutLocal1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { Goo(out [|bar|]); } static void Goo(out int i) { } }", @"class Program { void Main() { int bar; Goo(out bar); } static void Goo(out int i) { } }", index: ReadonlyFieldIndex); } [WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalBeforeComment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", @"class Program { void Main() { #if true int local; // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", index: ReadonlyFieldIndex); } [WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestLocalAfterComment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int.TryParse(""123"", out [|local|]); #endif } }", @"class Program { void Main() { #if true // Banner Line 1 // Banner Line 2 int local; int.TryParse(""123"", out [|local|]); #endif } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateIntoVisiblePortion() { await TestInRegularAndScriptAsync( @"using System; #line hidden class Program { void Main() { #line default Goo(Program.[|X|]) } }", @"using System; #line hidden class Program { void Main() { #line default Goo(Program.X) } public static object X { get; private set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingWhenNoAvailableRegionToGenerateInto() { await TestMissingInRegularAndScriptAsync( @"using System; #line hidden class Program { void Main() { #line default Goo(Program.[|X|]) #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalAvailableIfBlockIsNotHidden() { await TestInRegularAndScriptAsync( @"using System; #line hidden class Program { #line default void Main() { Goo([|x|]); } #line hidden } #line default", @"using System; #line hidden class Program { #line default void Main() { object x = null; Goo(x); } #line hidden } #line default"); } [WorkItem(545217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalNameSimplificationCSharp7() { await TestAsync( @"class Program { void goo() { bar([|xyz|]); } struct sfoo { } void bar(sfoo x) { } }", @"class Program { void goo() { sfoo xyz = default(sfoo); bar(xyz); } struct sfoo { } void bar(sfoo x) { } }", index: 3, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); } [WorkItem(545217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545217")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalNameSimplification() { await TestInRegularAndScriptAsync( @"class Program { void goo() { bar([|xyz|]); } struct sfoo { } void bar(sfoo x) { } }", @"class Program { void goo() { sfoo xyz = default; bar(xyz); } struct sfoo { } void bar(sfoo x) { } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestParenthesizedExpression() { await TestInRegularAndScriptAsync( @"class Program { void Main() { int v = 1 + ([|k|]); } }", @"class Program { private int k; void Main() { int v = 1 + (k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInSelect() { await TestInRegularAndScriptAsync( @"using System.Linq; class Program { void Main(string[] args) { var q = from a in args select [|v|]; } }", @"using System.Linq; class Program { private object v; void Main(string[] args) { var q = from a in args select v; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInChecked() { await TestInRegularAndScriptAsync( @"class Program { void Main() { int[] a = null; int[] temp = checked([|goo|]); } }", @"class Program { private int[] goo; void Main() { int[] a = null; int[] temp = checked(goo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInArrayRankSpecifier() { await TestInRegularAndScriptAsync( @"class Program { void Main() { var v = new int[[|k|]]; } }", @"class Program { private int k; void Main() { var v = new int[k]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional1() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = [|goo|] ? bar : baz; } }", @"class Program { private static bool goo; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional2() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = goo ? [|bar|] : baz; } }", @"class Program { private static int bar; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInConditional3() { await TestInRegularAndScriptAsync( @"class Program { static void Main() { int i = goo ? bar : [|baz|]; } }", @"class Program { private static int baz; static void Main() { int i = goo ? bar : baz; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInCast() { await TestInRegularAndScriptAsync( @"class Program { void Main() { var x = (int)[|y|]; } }", @"class Program { private int y; void Main() { var x = (int)y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInIf() { await TestInRegularAndScriptAsync( @"class Program { void Main() { if ([|goo|]) { } } }", @"class Program { private bool goo; void Main() { if (goo) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInSwitch() { await TestInRegularAndScriptAsync( @"class Program { void Main() { switch ([|goo|]) { } } }", @"class Program { private int goo; void Main() { switch (goo) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnNamespace() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnType() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOnBase() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { [|base|].ToString(); } }"); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign1() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = 1; } }", @"class Program { void Main() { var undefined = 1; } }", index: PropertyIndex, options: ImplicitTypingEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestFuncAssignment() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = (x) => 2; } }", @"class Program { void Main() { System.Func<object, int> undefined = (x) => 2; } }", index: PropertyIndex); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign1NotAsVar() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = 1; } }", @"class Program { void Main() { int undefined = 1; } }", index: PropertyIndex); } [WorkItem(545273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545273")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFromAssign2() { await TestInRegularAndScriptAsync( @"class Program { void Main() { [|undefined|] = new { P = ""1"" }; } }", @"class Program { void Main() { var undefined = new { P = ""1"" }; } }", index: PropertyIndex); } [WorkItem(545269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInVenus1() { await TestMissingInRegularAndScriptAsync( @"class C { #line 1 ""goo"" void Goo() { this.[|Bar|] = 1; } #line default #line hidden }"); } [WorkItem(545269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInVenus2() { var code = @" class C { #line 1 ""goo"" void Goo() { [|Bar|] = 1; } #line default #line hidden } "; await TestExactActionSetOfferedAsync(code, new[] { string.Format(FeaturesResources.Generate_local_0, "Bar"), string.Format(FeaturesResources.Generate_parameter_0, "Bar") }); await TestInRegularAndScriptAsync(code, @" class C { #line 1 ""goo"" void Goo() { var [|Bar|] = 1; } #line default #line hidden } ", options: ImplicitTypingEverywhere()); } [WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyFromAttribute() { await TestInRegularAndScriptAsync( @"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [MyAttr(123, [|Value|] = 1)] class D { }", @"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { public int Value { get; set; } } [MyAttr(123, Value = 1)] class D { }"); } [WorkItem(545232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545232")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNewLinePreservationBeforeInsertingLocal() { await TestInRegularAndScriptAsync( @"using System; namespace CSharpDemoApp { class Program { static void Main(string[] args) { const int MEGABYTE = 1024 * 1024; Console.WriteLine(MEGABYTE); Calculate([|multiplier|]); } static void Calculate(double multiplier = Math.PI) { } } } ", @"using System; namespace CSharpDemoApp { class Program { static void Main(string[] args) { const int MEGABYTE = 1024 * 1024; Console.WriteLine(MEGABYTE); double multiplier = 0; Calculate(multiplier); } static void Calculate(double multiplier = Math.PI) { } } } ", index: LocalIndex); } [WorkItem(863346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod_Local() { await TestInRegularAndScriptAsync( @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { T t = WrapFunc<T>([|NewLocal|]); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { Func<T1, T> NewLocal = null; T t = WrapFunc<T>(NewLocal); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", index: LocalIndex); } [WorkItem(863346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863346")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateInGenericMethod_Property() { await TestInRegularAndScriptAsync( @"using System; class TestClass<T1> { static T TestMethod<T>(T item) { T t = WrapFunc<T>([|NewLocal|]); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } ", @"using System; class TestClass<T1> { public static Func<T1, object> NewLocal { get; private set; } static T TestMethod<T>(T item) { T t = WrapFunc<T>(NewLocal); return t; } private static T WrapFunc<T>(Func<T1, T> function) { T1 zoo = default(T1); return function(zoo); } } "); } [WorkItem(865067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865067")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInMethod() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { IEnumerable<DayOfWeek> Goo() { yield return [|abc|]; } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; IEnumerable<DayOfWeek> Goo() { yield return abc; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInAsyncMethod() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { async IAsyncEnumerable<DayOfWeek> Goo() { yield return [|abc|]; } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; async IAsyncEnumerable<DayOfWeek> Goo() { yield return abc; } }"); } [WorkItem(30235, "https://github.com/dotnet/roslyn/issues/30235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithYieldReturnInLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void M() { IEnumerable<DayOfWeek> F() { yield return [|abc|]; } } }", @"using System; using System.Collections.Generic; class Program { private DayOfWeek abc; void M() { IEnumerable<DayOfWeek> F() { yield return abc; } } }"); } [WorkItem(877580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/877580")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithThrow() { await TestInRegularAndScriptAsync( @"using System; class Program { void Goo() { throw [|MyExp|]; } }", @"using System; class Program { private Exception MyExp; void Goo() { throw MyExp; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { private unsafe int* goo; void Method() { int* a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { private unsafe int*[] goo; void Method() { int*[] a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { private int* goo; void Method() { int* a = goo; } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { private int* goo; void Method() { int* a = goo; } } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeFieldInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { private static unsafe int* goo; unsafe class MyClass { void Method() { int* a = Class.goo; } } }"); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyField() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { private readonly unsafe int* goo; void Method() { int* a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyField2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { private readonly unsafe int*[] goo; void Method() { int*[] a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { private readonly int* goo; void Method() { int* a = goo; } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { private readonly int* goo; void Method() { int* a = goo; } } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeReadOnlyFieldInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { private static readonly unsafe int* goo; unsafe class MyClass { void Method() { int* a = Class.goo; } } }", index: ReadonlyFieldIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeProperty() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int* a = goo|]; } }", @"class Class { public unsafe int* goo { get; private set; } void Method() { int* a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafeProperty2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|int*[] a = goo|]; } }", @"class Class { public unsafe int*[] goo { get; private set; } void Method() { int*[] a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInUnsafeClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { void Method() { [|int* a = goo|]; } }", @"unsafe class Class { public int* goo { get; private set; } void Method() { int* a = goo; } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInNestedClass() { await TestInRegularAndScriptAsync( @"unsafe class Class { class MyClass { void Method() { [|int* a = goo|]; } } }", @"unsafe class Class { class MyClass { public int* goo { get; private set; } void Method() { int* a = goo; } } }", index: PropertyIndex); } [WorkItem(530177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530177")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestUnsafePropertyInNestedClass2() { await TestInRegularAndScriptAsync( @"class Class { unsafe class MyClass { void Method() { [|int* a = Class.goo|]; } } }", @"class Class { public static unsafe int* goo { get; private set; } unsafe class MyClass { void Method() { int* a = Class.goo; } } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { private object Z; void M() { var x = nameof(Z); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z.X); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { private object Z; void M() { var x = nameof(Z.X); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z.X); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal2() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z.X); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { public object Z { get; private set; } void M() { var x = nameof(Z.X.Y); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { private object Z; void M() { var x = nameof(Z.X.Y); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { private readonly object Z; void M() { var x = nameof(Z.X.Y); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal3() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|Z.X.Y|]); } }", @"class C { void M() { object Z = null; var x = nameof(Z.X.Y); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var x = [|nameof(1 + 2)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var y = 1 + 2; var x = [|nameof(y)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfMissing3() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var y = 1 + 2; var z = """"; var x = [|nameof(y, z)|]; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { public object y { get; private set; } void M() { var x = nameof(y, z); } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { private object y; void M() { var x = nameof(y, z); } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { private readonly object y; void M() { var x = nameof(y, z); } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal4() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|], z); } }", @"class C { void M() { object y = null; var x = nameof(y, z); } }", index: LocalIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfProperty5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { public object y { get; private set; } void M() { var x = nameof(y); } private object nameof(object y) { return null; } }", index: PropertyIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfField5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { private object y; void M() { var x = nameof(y); } private object nameof(object y) { return null; } }"); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfReadonlyField5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { private readonly object y; void M() { var x = nameof(y); } private object nameof(object y) { return null; } }", index: ReadonlyFieldIndex); } [WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestInsideNameOfLocal5() { await TestInRegularAndScriptAsync( @"class C { void M() { var x = nameof([|y|]); } private object nameof(object y) { return null; } }", @"class C { void M() { object y = null; var x = nameof(y); } private object nameof(object y) { return null; } }", index: LocalIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { public C Instance { get; private set; } void Main(C a) { C x = a?.Instance; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { private C Instance; void Main(C a) { C x = a?.Instance; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { C x = a?[|.Instance|]; } }", @"class C { private readonly C Instance; void Main(C a) { C x = a?.Instance; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { public object Instance { get; private set; } void Main(C a) { var x = a?.Instance; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { private object Instance; void Main(C a) { var x = a?.Instance; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessVarReadOnlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { var x = a?[|.Instance|]; } }", @"class C { private readonly object Instance; void Main(C a) { var x = a?.Instance; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableProperty() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { public int B { get; private set; } void Main(C a) { int? x = a?.B; } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { private int B; void Main(C a) { int? x = a?.B; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConditionalAccessNullableReadonlyField() { await TestInRegularAndScriptAsync( @"class C { void Main(C a) { int? x = a?[|.B|]; } }", @"class C { private readonly int B; void Main(C a) { int? x = a?.B; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { public C C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { public int C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { public int C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { public object C { get; internal set; } } }"); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { internal C C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { internal int C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { internal int C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { internal object C; } }", index: ReadonlyFieldIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { C x = a?.B.C; } public class E { internal readonly C C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression2() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int x = a?.B.C; } public class E { internal readonly int C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression3() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { int? x = a?.B.C; } public class E { internal readonly int C; } }", index: PropertyIndex); } [WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInConditionalAccessExpression4() { await TestInRegularAndScriptAsync( @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.[|C|]; } public class E { } }", @"class C { public E B { get; private set; } void Main(C a) { var x = a?.B.C; } public class E { internal readonly object C; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { private static int y; public int MyProperty { get; } = y; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { private static readonly int y; public int MyProperty { get; } = y; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInPropertyInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public int MyProperty { get; } = [|y|]; }", @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public static int y { get; private set; } public int MyProperty { get; } = y; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { private int y; public int Y => y; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { private readonly int y; public int Y => y; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedProperty() { await TestInRegularAndScriptAsync( @"class Program { public int Y => [|y|]; }", @"class Program { public int Y => y; public int y { get; private set; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { private static C x; public static C operator --(C p) => x; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { private static readonly C x; public static C operator --(C p) => x; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedOperator() { await TestInRegularAndScriptAsync( @"class C { public static C operator --(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static C operator --(C p) => x; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { private static C x; public static C GetValue(C p) => x; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { private static readonly C x; public static C GetValue(C p) => x; }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedMethod() { await TestInRegularAndScriptAsync( @"class C { public static C GetValue(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static C GetValue(C p) => x; }", index: PropertyIndex); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTMethod() { await TestInRegularAndScriptAsync( @"class C { public static async System.Threading.Tasks.Task<C> GetValue(C p) => [|x|]; }", @"class C { public static C x { get; private set; } public static async System.Threading.Tasks.Task<C> GetValue(C p) => x; }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { private static string key; static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { public static string One { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { private static int i; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { private static readonly string key; static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { private static string One; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { private static readonly int i; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { public static string key { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [key] = 0 }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyFieldInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { private static readonly string One; static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { public static int i { get; private set; } static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [[|key|]] = 0 }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { string key = null; var x = new Dictionary<string, int> { [key] = 0 }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = 0, [[|One|]] = 1, [""Two""] = 2 }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { string One = null; var x = new Dictionary<string, int> { [""Zero""] = 0, [One] = 1, [""Two""] = 2 }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateLocalInDictionaryInitializer3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int> { [""Zero""] = [|i|] }; } }", @"using System.Collections.Generic; class Program { static void Main(string[] args) { int i = 0; var x = new Dictionary<string, int> { [""Zero""] = i }; } }", index: LocalIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { private static Func<int> goo; static void Main(string[] args) { goo = () => { return 0; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda2() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { public static Func<int> goo { get; private set; } static void Main(string[] args) { goo = () => { return 0; }; } }", index: ReadonlyFieldIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateVariableFromLambda3() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|goo|] = () => { return 0; }; } }", @"using System; class Program { static void Main(string[] args) { Func<int> goo = () => { return 0; }; } }", index: PropertyIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Field() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { private static int _field; public static int Property1 { get { return _field; } } }"); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_ReadonlyField() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { private static readonly int _field; public static int Property1 { get { return _field; } } }", index: ReadonlyFieldIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Property() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { public static int Property1 { get { return _field; } } public static int _field { get; private set; } }", index: PropertyIndex); } [WorkItem(8010, "https://github.com/dotnet/roslyn/issues/8010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerationFromStaticProperty_Local() { await TestInRegularAndScriptAsync( @"using System; public class Test { public static int Property1 { get { return [|_field|]; } } }", @"using System; public class Test { public static int Property1 { get { int _field = 0; return _field; } } }", index: LocalIndex); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestSameNameAsInstanceVariableInContainingType() { await TestInRegularAndScriptAsync( @"class Outer { int _field; class Inner { public Inner(int field) { [|_field|] = field; } } }", @"class Outer { int _field; class Inner { private int _field; public Inner(int field) { _field = field; } } }"); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnStaticWithExistingInstance1() { await TestMissingInRegularAndScriptAsync( @"class C { int _field; void M() { C.[|_field|] = 42; } }"); } [WorkItem(8358, "https://github.com/dotnet/roslyn/issues/8358")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnStaticWithExistingInstance2() { await TestMissingInRegularAndScriptAsync( @"class C { int _field; static C() { [|_field|] = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRead() { await TestInRegularAndScriptAsync( @"class Class { void Method((int, string) i) { Method([|tuple|]); } }", @"class Class { private (int, string) tuple; void Method((int, string) i) { Method(tuple); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWithOneNameRead() { await TestInRegularAndScriptAsync( @"class Class { void Method((int a, string) i) { Method([|tuple|]); } }", @"class Class { private (int a, string) tuple; void Method((int a, string) i) { Method(tuple); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWrite() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|tuple|] = (1, ""hello""); } }", @"class Class { private (int, string) tuple; void Method() { tuple = (1, ""hello""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleWithOneNameWrite() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|tuple|] = (a: 1, ""hello""); } }", @"class Class { private (int a, string) tuple; void Method() { tuple = (a: 1, ""hello""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRefReturnProperties() { await TestInRegularAndScriptAsync( @" using System; class C { public void Goo() { ref int i = ref this.[|Bar|]; } }", @" using System; class C { public ref int Bar => throw new NotImplementedException(); public void Goo() { ref int i = ref this.Bar; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TupleRefWithField() { await TestInRegularAndScriptAsync( @" using System; class C { public void Goo() { ref int i = ref this.[|bar|]; } }", @" using System; class C { private int bar; public void Goo() { ref int i = ref this.bar; } }"); } [WorkItem(17621, "https://github.com/dotnet/roslyn/issues/17621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithMatchingTypeName1() { await TestInRegularAndScript1Async( @" using System; public class Goo { public Goo(String goo) { [|String|] = goo; } }", @" using System; public class Goo { public Goo(String goo) { String = goo; } public string String { get; } }"); } [WorkItem(17621, "https://github.com/dotnet/roslyn/issues/17621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithMatchingTypeName2() { await TestInRegularAndScript1Async( @" using System; public class Goo { public Goo(String goo) { [|String|] = goo; } }", @" using System; public class Goo { public Goo(String goo) { String = goo; } public string String { get; private set; } }", index: ReadonlyFieldIndex); } [WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestContextualKeyword1() { await TestMissingInRegularAndScriptAsync( @" namespace N { class nameof { } } class C { void M() { [|nameof|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreferReadOnlyIfAfterReadOnlyAssignment() { await TestInRegularAndScriptAsync( @"class Class { private readonly int _goo; public Class() { _goo = 0; [|_bar|] = 1; } }", @"class Class { private readonly int _goo; private readonly int _bar; public Class() { _goo = 0; _bar = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPreferReadOnlyIfBeforeReadOnlyAssignment() { await TestInRegularAndScriptAsync( @"class Class { private readonly int _goo; public Class() { [|_bar|] = 1; _goo = 0; } }", @"class Class { private readonly int _bar; private readonly int _goo; public Class() { _bar = 1; _goo = 0; } }"); } [WorkItem(19239, "https://github.com/dotnet/roslyn/issues/19239")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadOnlyPropertyInConstructor() { await TestInRegularAndScriptAsync( @"class Class { public Class() { [|Bar|] = 1; } }", @"class Class { public Class() { Bar = 1; } public int Bar { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlaceFieldBasedOnSurroundingStatements() { await TestInRegularAndScriptAsync( @"class Class { private int _goo; private int _quux; public Class() { _goo = 0; [|_bar|] = 1; _quux = 2; } }", @"class Class { private int _goo; private int _bar; private int _quux; public Class() { _goo = 0; _bar = 1; _quux = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlaceFieldBasedOnSurroundingStatements2() { await TestInRegularAndScriptAsync( @"class Class { private int goo; private int quux; public Class() { this.goo = 0; this.[|bar|] = 1; this.quux = 2; } }", @"class Class { private int goo; private int bar; private int quux; public Class() { this.goo = 0; this.bar = 1; this.quux = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPlacePropertyBasedOnSurroundingStatements() { await TestInRegularAndScriptAsync( @"class Class { public int Goo { get; } public int Quuz { get; } public Class() { Goo = 0; [|Bar|] = 1; Quux = 2; } }", @"class Class { public int Goo { get; } public int Bar { get; } public int Quuz { get; } public Class() { Goo = 0; Bar = 1; Quux = 2; } }"); } [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNotOnGenericCodeParsedAsExpression() { await TestMissingAsync(@" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 > return ImmutableArray.CreateRange(); } }"); } [WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestOnNonGenericExpressionWithLessThan() { await TestInRegularAndScriptAsync(@" class C { private void GetEvaluationRuleNames() { [|IEnumerable|] < Int32 return ImmutableArray.CreateRange(); } }", @" class C { public int IEnumerable { get; private set; } private void GetEvaluationRuleNames() { IEnumerable < Int32 return ImmutableArray.CreateRange(); } }"); } [WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task GroupNonReadonlyFieldsTogether() { await TestInRegularAndScriptAsync(@" class C { public bool isDisposed; public readonly int x; public readonly int m; public C() { this.[|y|] = 0; } }", @" class C { public bool isDisposed; private int y; public readonly int x; public readonly int m; public C() { this.y = 0; } }"); } [WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task GroupReadonlyFieldsTogether() { await TestInRegularAndScriptAsync(@" class C { public readonly int x; public readonly int m; public bool isDisposed; public C() { this.[|y|] = 0; } }", @" class C { public readonly int x; public readonly int m; private readonly int y; public bool isDisposed; public C() { this.y = 0; } }", index: ReadonlyFieldIndex); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithOutOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo(out [|goo|]); } void Goo(int i) { } void Goo(out bool b) { } }", @"class Class { private bool goo; void Method() { Goo(out goo); } void Goo(int i) { } void Goo(out bool b) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithOutOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo([|goo|]); } void Goo(out bool b) { } void Goo(int i) { } }", @"class Class { private int goo; void Method() { Goo(goo); } void Goo(out bool b) { } void Goo(int i) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithRefOverload1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo(ref [|goo|]); } void Goo(int i) { } void Goo(ref bool b) { } }", @"class Class { private bool goo; void Method() { Goo(ref goo); } void Goo(int i) { } void Goo(ref bool b) { } }"); } [WorkItem(20791, "https://github.com/dotnet/roslyn/issues/20791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestWithRefOverload2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { Goo([|goo|]); } void Goo(ref bool b) { } void Goo(int i) { } }", @"class Class { private int goo; void Method() { Goo(goo); } void Goo(ref bool b) { } void Goo(int i) { } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|_field|]; } }", @"class Program { private int _field; public int Property { get => _field; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedGetterWithDifferentAccessibility() { await TestInRegularAndScriptAsync( @"class Program { public int Property { protected get => [|_field|]; set => throw new System.NotImplementedException(); } }", @"class Program { private int _field; public int Property { protected get => _field; set => throw new System.NotImplementedException(); } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|_readonlyField|]; } }", @"class Program { private readonly int _readonlyField; public int Property { get => _readonlyField; } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedGetter() { await TestInRegularAndScriptAsync( @"class Program { public int Property { get => [|prop|]; } }", @"class Program { public int Property { get => prop; } public int prop { get; private set; } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedSetterInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public int Property { set => [|_field|] = value; } }", @"class Program { private int _field; public int Property { set => _field = value; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_field|]; } }", @"class Program { private int _field; public void Method() { int Local() => _field; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_readonlyField|]; } }", @"class Program { private readonly int _readonlyField; public void Method() { int Local() => _readonlyField; } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|prop|]; } }", @"class Program { public int prop { get; private set; } public void Method() { int Local() => prop; } }", index: PropertyIndex); } [WorkItem(27647, "https://github.com/dotnet/roslyn/issues/27647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInExpressionBodiedAsyncTaskOfTLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { async System.Threading.Tasks.Task<int> Local() => [|prop|]; } }", @"class Program { public int prop { get; private set; } public void Method() { async System.Threading.Tasks.Task<int> Local() => prop; } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() => [|_field|] = 12; } }", @"class Program { private int _field; public void Method() { int Local() => _field = 12; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_field|]; } } }", @"class Program { private int _field; public void Method() { int Local() { return _field; } } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateReadonlyFieldInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_readonlyField|]; } } }", @"class Program { private readonly int _readonlyField; public void Method() { int Local() { return _readonlyField; } } }", index: ReadonlyFieldIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInBlockBodiedLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|prop|]; } } }", @"class Program { public int prop { get; private set; } public void Method() { int Local() { return prop; } } }", index: PropertyIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGeneratePropertyInBlockBodiedAsyncTaskOfTLocalFunction() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { async System.Threading.Tasks.Task<int> Local() { return [|prop|]; } } }", @"class Program { public int prop { get; private set; } public void Method() { async System.Threading.Tasks.Task<int> Local() { return prop; } } }", index: PropertyIndex); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunctionInferredFromType() { await TestInRegularAndScriptAsync( @"class Program { public void Method() { int Local() { return [|_field|] = 12; } } }", @"class Program { private int _field; public void Method() { int Local() { return _field = 12; } } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInBlockBodiedLocalFunctionInsideLambdaExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { public void Method() { Action action = () => { int Local() { return [|_field|]; } }; } }", @" using System; class Program { private int _field; public void Method() { Action action = () => { int Local() { return _field; } }; } }"); } [WorkItem(26993, "https://github.com/dotnet/roslyn/issues/26993")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestGenerateFieldInExpressionBodiedLocalFunctionInsideLambdaExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { public void Method() { Action action = () => { int Local() => [|_field|]; }; } }", @" using System; class Program { private int _field; public void Method() { Action action = () => { int Local() => _field; }; } }"); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock1() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { private object goo; void Method() { lock (goo) { } } }"); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock2() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { private readonly object goo; void Method() { lock (goo) { } } }", index: 1); } [WorkItem(26406, "https://github.com/dotnet/roslyn/issues/26406")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestIdentifierInsideLock3() { await TestInRegularAndScriptAsync( @"class Class { void Method() { lock ([|goo|]) { } } }", @"class Class { public object goo { get; private set; } void Method() { lock (goo) { } } }", index: 2); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: int i }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: int i }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern2() { await TestInRegularAndScriptAsync( @" class C { void M2() { Blah o = null; if (o is { [|X|]: int i }) { } } class Blah { } }", @" class C { void M2() { Blah o = null; if (o is { X: int i }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern3() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { X: { [|Y|]: int i } }) { } } class Frob { } class Blah { public Frob X; } }", @" class C { void M2() { object o = null; if (o is Blah { X: { Y: int i } }) { } } class Frob { public int Y { get; internal set; } } class Blah { public Frob X; } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern4() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: }) { } } class Blah { public object X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern5() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: Frob { } }) { } } class Blah { } class Frob { } }", @" class C { void M2() { object o = null; if (o is Blah { X: Frob { } }) { } } class Blah { public Frob X { get; internal set; } } class Frob { } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern6() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (1, 2) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (1, 2) }) { } } class Blah { public (int, int) X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern7() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (y: 1, z: 2) }) { } } class Blah { } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, @" class C { void M2() { object o = null; if (o is Blah { X: (y: 1, z: 2) }) { } } class Blah { public (int y, int z) X { get; internal set; } } } " + TestResources.NetFX.ValueTuple.tuplelib_cs); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern8() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: () }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: () }) { } } class Blah { public object X { get; internal set; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestExtendedPropertyPatternInIsPattern() { await TestInRegularAndScriptAsync( @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah.[|X|]: (y: 1, z: 2) }) { } } class Blah { } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah.X: (y: 1, z: 2) }) { } } class Blah { public (int y, int z) X { get; internal set; } } } " + TestResources.NetFX.ValueTuple.tuplelib_cs, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantPatternInPropertyPattern() { await TestInRegularAndScriptAsync( @" class C { Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah: [|MissingConstant|] }) { } } class Blah { } } ", @" class C { private const Blah MissingConstant; Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeBlah: MissingConstant }) { } } class Blah { } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestConstantPatternInExtendedPropertyPattern() { await TestInRegularAndScriptAsync( @" class C { C SomeC { get; set; } Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeC.SomeBlah: [|MissingConstant|] }) { } } class Blah { } } ", @" class C { private const Blah MissingConstant; C SomeC { get; set; } Blah SomeBlah { get; set; } void M2() { object o = null; if (o is C { SomeC.SomeBlah: MissingConstant }) { } } class Blah { } } ", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern9() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (1) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (1) }) { } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPattern10() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; if (o is Blah { [|X|]: (y: 1) }) { } } class Blah { } }", @" class C { void M2() { object o = null; if (o is Blah { X: (y: 1) }) { } } class Blah { public object X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsPatternWithNullablePattern() { await TestInRegularAndScriptAsync( @"#nullable enable class C { void M2() { object? o = null; object? zToMatch = null; if (o is Blah { [|X|]: (y: 1, z: zToMatch) }) { } } class Blah { } }", @"#nullable enable class C { void M2() { object? o = null; object? zToMatch = null; if (o is Blah { X: (y: 1, z: zToMatch) }) { } } class Blah { public (int y, object? z) X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInCasePattern1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; switch (o) { case Blah { [|X|]: int i }: break; } } class Blah { } }", @" class C { void M2() { object o = null; switch (o) { case Blah { X: int i }: break; } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInCasePattern2() { await TestInRegularAndScriptAsync( @" class C { void M2() { Blah o = null; switch (o) { case { [|X|]: int i }: break; } } class Blah { } }", @" class C { void M2() { Blah o = null; switch (o) { case { X: int i }: break; } } class Blah { public int X { get; internal set; } } }"); } [WorkItem(9090, "https://github.com/dotnet/roslyn/issues/9090")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternInIsSwitchExpression1() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; _ = o switch { Blah { [|X|]: int i } => 0, _ => 0 }; } class Blah { } }", @" class C { void M2() { object o = null; _ = o switch { Blah { X: int i } => 0, _ => 0 }; } class Blah { public int X { get; internal set; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestPropertyPatternGenerateConstant() { await TestInRegularAndScriptAsync( @" class C { void M2() { object o = null; _ = o switch { Blah { X: [|Y|] } => 0, _ => 0 }; } class Blah { public int X; } }", @" class C { private const int Y; void M2() { object o = null; _ = o switch { Blah { X: Y } => 0, _ => 0 }; } class Blah { public int X; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameter() { await TestInRegularAndScriptAsync( @"class Class { void Method() { [|goo|]; } }", @"class Class { void Method(object goo) { goo; } }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameter_DoesntAddToInterface() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class { public void Method() { [|goo|]; } }", @"interface Interface { void Method(); } class Class { public void Method(object goo) { [|goo|]; } }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterAndOverrides_AddsToInterface() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class : Interface { public void Method() { [|goo|]; } }", @"interface Interface { void Method(object goo); } class Class : Interface { public void Method(object goo) { [|goo|]; } }", index: ParameterAndOverrides); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterIsOfCorrectType() { await TestInRegularAndScriptAsync( @"class Class { void Method() { M1([|goo|]); } void M1(int a); }", @"class Class { void Method(int goo) { M1(goo); } void M1(int a); }", index: Parameter); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestAddParameterAndOverrides_IsOfCorrectType() { await TestInRegularAndScriptAsync( @"interface Interface { void Method(); } class Class : Interface { public void Method() { M1([|goo|]); } void M1(int a); }", @"interface Interface { void Method(int goo); } class Class : Interface { public void Method(int goo) { M1(goo); } void M1(int a); }", index: ParameterAndOverrides); } [WorkItem(26502, "https://github.com/dotnet/roslyn/issues/26502")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoReadOnlyMembersWhenInLambdaInConstructor() { await TestExactActionSetOfferedAsync( @"using System; class C { public C() { Action a = () => { this.[|Field|] = 1; }; } }", new[] { string.Format(FeaturesResources.Generate_property_1_0, "Field", "C"), string.Format(FeaturesResources.Generate_field_1_0, "Field", "C"), }); } [WorkItem(26502, "https://github.com/dotnet/roslyn/issues/26502")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestNoReadOnlyMembersWhenInLocalFunctionInConstructor() { await TestExactActionSetOfferedAsync( @"using System; class C { public C() { void Goo() { this.[|Field|] = 1; }; } }", new[] { string.Format(FeaturesResources.Generate_property_1_0, "Field", "C"), string.Format(FeaturesResources.Generate_field_1_0, "Field", "C"), }); } [WorkItem(45367, "https://github.com/dotnet/roslyn/issues/45367")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task DontOfferPropertyOrFieldInNamespace() { await TestExactActionSetOfferedAsync( @"using System; namespace ConsoleApp5 { class MyException: Exception internal MyException(int error, int offset, string message) : base(message) { [|Error|] = error; Offset = offset; }", new[] { string.Format(FeaturesResources.Generate_local_0, "Error", "MyException"), string.Format(FeaturesResources.Generate_parameter_0, "Error", "MyException"), }); } [WorkItem(48172, "https://github.com/dotnet/roslyn/issues/48172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)] public async Task TestMissingOfferParameterInTopLevel() { await TestMissingAsync("[|Console|].WriteLine();", new TestParameters(Options.Regular)); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaRemoteServiceCallbackIdWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { [DataContract] internal readonly struct PythiaRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { [DataContract] internal readonly struct PythiaRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard { private readonly CSharpCompilation _compilation; private readonly SyntheticBoundNodeFactory _factory; private readonly SynthesizedSubmissionFields _previousSubmissionFields; private readonly bool _allowOmissionOfConditionalCalls; private LoweredDynamicOperationFactory _dynamicFactory; private bool _sawLambdas; private int _availableLocalFunctionOrdinal; private bool _inExpressionLambda; private bool _sawAwait; private bool _sawAwaitInExceptionHandler; private bool _needsSpilling; private readonly BindingDiagnosticBag _diagnostics; private Instrumenter _instrumenter; private readonly BoundStatement _rootStatement; private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly; private LocalRewriter( CSharpCompilation compilation, MethodSymbol containingMethod, int containingMethodOrdinal, BoundStatement rootStatement, NamedTypeSymbol? containingType, SyntheticBoundNodeFactory factory, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, BindingDiagnosticBag diagnostics, Instrumenter instrumenter) { _compilation = compilation; _factory = factory; _factory.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal); _previousSubmissionFields = previousSubmissionFields; _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls; _diagnostics = diagnostics; Debug.Assert(instrumenter != null); #if DEBUG // Ensure that only expected kinds of instrumenters are in use _ = RemoveDynamicAnalysisInjectors(instrumenter); #endif _instrumenter = instrumenter; _rootStatement = rootStatement; } /// <summary> /// Lower a block of code by performing local rewritings. /// </summary> public static BoundStatement Rewrite( CSharpCompilation compilation, MethodSymbol method, int methodOrdinal, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, bool instrumentForDynamicAnalysis, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, DebugDocumentProvider debugDocumentProvider, BindingDiagnosticBag diagnostics, out bool sawLambdas, out bool sawLocalFunctions, out bool sawAwaitInExceptionHandler) { Debug.Assert(statement != null); Debug.Assert(compilationState != null); try { var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics); DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null; // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not. // Presence of sequence points in the tree affects final IL, therefore, we always generate them. var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics, dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton); statement.CheckLocalsDefined(); var loweredStatement = localRewriter.VisitStatement(statement); Debug.Assert(loweredStatement is { }); loweredStatement.CheckLocalsDefined(); sawLambdas = localRewriter._sawLambdas; sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0; sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler; if (localRewriter._needsSpilling && !loweredStatement.HasErrors) { // Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression. var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics); spilledStatement.CheckLocalsDefined(); loweredStatement = spilledStatement; } if (dynamicInstrumenter != null) { dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans; } #if DEBUG LocalRewritingValidator.Validate(loweredStatement); #endif return loweredStatement; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false; return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true); } } private bool Instrument { get { return !_inExpressionLambda; } } private PEModuleBuilder? EmitModule { get { return _factory.CompilationState.ModuleBuilderOpt; } } /// <summary> /// Return the translated node, or null if no code is necessary in the translation. /// </summary> public override BoundNode? Visit(BoundNode? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); BoundExpression? expr = node as BoundExpression; if (expr != null) { return VisitExpressionImpl(expr); } return node.Accept(this); } [return: NotNullIfNotNull("node")] private BoundExpression? VisitExpression(BoundExpression? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); // https://github.com/dotnet/roslyn/issues/47682 return VisitExpressionImpl(node)!; } private BoundStatement? VisitStatement(BoundStatement? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); return (BoundStatement?)node.Accept(this); } private BoundExpression? VisitExpressionImpl(BoundExpression node) { ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { TypeSymbol? type = node.Type; if (type?.IsNullableType() != true) { return MakeLiteral(node.Syntax, constantValue, type); } } var visited = VisitExpressionWithStackGuard(node); // If you *really* need to change the type, consider using an indirect method // like compound assignment does (extra flag only passed when it is an expression // statement means that this constraint is not violated). // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees. // Unused deconstructions are lowered to produce a return value that isn't a tuple type. Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) || visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || IsUnusedDeconstruction(node)); if (visited != null && visited != node && node.Kind != BoundKind.ImplicitReceiver && node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder) { if (!CanBePassedByReference(node) && CanBePassedByReference(visited)) { visited = RefAccessMustMakeCopy(visited); } } return visited; } private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited) { visited = new BoundPassByCopy( visited.Syntax, visited, type: visited.Type); return visited; } private static bool IsUnusedDeconstruction(BoundExpression node) { return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed; } public override BoundNode VisitLambda(BoundLambda node) { _sawLambdas = true; var lambda = node.Symbol; CheckRefReadOnlySymbols(lambda); var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; try { _factory.CurrentFunction = lambda; if (lambda.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } return base.VisitLambda(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; } } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { int localFunctionOrdinal = _availableLocalFunctionOrdinal++; var localFunction = node.Symbol; CheckRefReadOnlySymbols(localFunction); if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder) { var typeParameters = localFunction.TypeParameters; if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint)) { moduleBuilder.EnsureIsUnmanagedAttributeExists(); } if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) || typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger()))) { moduleBuilder.EnsureNativeIntegerAttributeExists(); } if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction)) { bool constraintsNeedNullableAttribute = typeParameters.Any( typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute()); if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute())) { moduleBuilder.EnsureNullableAttributeExists(); } } static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) => predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate); } var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; var oldDynamicFactory = _dynamicFactory; try { _factory.CurrentFunction = localFunction; if (localFunction.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } if (localFunction.IsGenericMethod) { // Each generic local function gets its own dynamic factory because it // needs its own container to cache dynamic call-sites. That type (the container) "inherits" // local function's type parameters as well as type parameters of all containing methods. _dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal); } return base.VisitLocalFunctionStatement(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; _dynamicFactory = oldDynamicFactory; } } private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter) { switch (instrumenter) { case DynamicAnalysisInjector { Previous: var previous }: return RemoveDynamicAnalysisInjectors(previous); case DebugInfoInjector { Previous: var previous } injector: var newPrevious = RemoveDynamicAnalysisInjectors(previous); if ((object)newPrevious == previous) { return injector; } else if ((object)newPrevious == Instrumenter.NoOp) { return DebugInfoInjector.Singleton; } else { return new DebugInfoInjector(previous); } case CompoundInstrumenter compound: // If we hit this it means a new kind of compound instrumenter is in use. // Either add a new case or add an abstraction that lets us // filter out the unwanted injectors in a more generalized way. throw ExceptionUtilities.UnexpectedValue(compound); default: Debug.Assert((object)instrumenter == Instrumenter.NoOp); return instrumenter; } } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return PlaceholderReplacement(node); } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { if (_inExpressionLambda) { // Expression trees do not include the 'this' argument for members. return node; } return PlaceholderReplacement(node); } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) => PlaceholderReplacement(node); public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) => PlaceholderReplacement(node); /// <summary> /// Returns substitution currently used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is no substitution. /// </summary> private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); var value = _placeholderReplacementMapDoNotUseDirectly[placeholder]; AssertPlaceholderReplacement(placeholder, value); return value; } [Conditional("DEBUG")] private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// Sets substitution used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is already a substitution. /// </summary> private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { AssertPlaceholderReplacement(placeholder, value); if (_placeholderReplacementMapDoNotUseDirectly is null) { _placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>(); } _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value); } /// <summary> /// Removes substitution currently used by the rewriter for a placeholder node. /// Asserts if there isn't already a substitution. /// </summary> private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder); Debug.Assert(removed); } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { // DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children since the BadExpression // may represent being unable to use the child as an lvalue or rvalue. return node; } private static BoundExpression BadExpression(BoundExpression node) { Debug.Assert(node.Type is { }); return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child) { return BadExpression(syntax, resultType, ImmutableArray.Create(child)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2) { return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children) { return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType); } private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol { Debug.Assert((syntax != null) ^ (location != null)); symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location); return symbol is { }; } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember) { return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { MethodSymbol method; if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method)) { return method; } else { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); SpecialType type = (SpecialType)descriptor.DeclaringTypeId; TypeSymbol container = compilation.Assembly.GetSpecialType(type); TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity); return new ErrorMethodSymbol(container, returnType, "Missing"); } } private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method) { return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method); } private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method) { return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method); } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType); Debug.Assert(sourceType is { }); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true); } return node.Update(sourceType, getTypeFromHandle, type); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var operand = this.VisitExpression(node.Operand); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true); } return node.Update(operand, getTypeFromHandle, type); } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { ImmutableArray<BoundStatement> originalStatements = node.Statements; var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length); foreach (var initializer in originalStatements) { if (IsFieldOrPropertyInitializer(initializer)) { if (initializer.Kind == BoundKind.Block) { var block = (BoundBlock)initializer; var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true); Debug.Assert(statement is { }); statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement))); } else { statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true)); } } else { statements.Add(VisitStatement(initializer)); } } int optimizedInitializers = 0; bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; for (int i = 0; i < statements.Count; i++) { var stmt = statements[i]; if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt))) { optimizedInitializers++; if (_factory.CurrentFunction?.IsStatic == false) { // NOTE: Dev11 removes static initializers if ONLY all of them are optimized out statements[i] = null; } } } ImmutableArray<BoundStatement> rewrittenStatements; if (optimizedInitializers == statements.Count) { // all are optimized away rewrittenStatements = ImmutableArray<BoundStatement>.Empty; statements.Free(); } else { // instrument remaining statements int remaining = 0; for (int i = 0; i < statements.Count; i++) { BoundStatement? rewritten = statements[i]; if (rewritten != null) { if (IsFieldOrPropertyInitializer(originalStatements[i])) { BoundStatement original = originalStatements[i]; if (Instrument && !original.WasCompilerGenerated) { rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten); } } statements[remaining] = rewritten; remaining++; } } statements.Count = remaining; // trim any trailing nulls rewrittenStatements = statements.ToImmutableAndFree()!; } return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { // An array access expression can be indexed using any of the following types: // * an integer primitive // * a System.Index // * a System.Range // The last two are only supported on SZArrays. For those cases we need to // lower into the appropriate helper methods. if (node.Indices.Length != 1) { return base.VisitArrayAccess(node)!; } var indexType = VisitType(node.Indices[0].Type); var F = _factory; BoundNode resultExpr; if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { // array[Index] is treated like a pattern-based System.Index indexing // expression, except that array indexers don't actually exist (they // don't have symbols) var arrayLocal = F.StoreToTemp( VisitExpression(node.Expression), out BoundAssignmentOperator arrayAssign); var indexOffsetExpr = MakePatternIndexOffsetExpression( node.Indices[0], F.ArrayLength(arrayLocal), out _); resultExpr = F.Sequence( ImmutableArray.Create(arrayLocal.LocalSymbol), ImmutableArray.Create<BoundExpression>(arrayAssign), F.ArrayAccess( arrayLocal, ImmutableArray.Create(indexOffsetExpr))); } else if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // array[Range] is compiled to: // System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range) Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array }); var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations; resultExpr = F.Call( receiver: null, F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T) .Construct(ImmutableArray.Create(elementType)), ImmutableArray.Create( VisitExpression(node.Expression), VisitExpression(node.Indices[0]))); } else { resultExpr = base.VisitArrayAccess(node)!; } return resultExpr; } internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer) { var syntax = initializer.Syntax; if (syntax.IsKind(SyntaxKind.Parameter)) { // This is an initialization of a generated property based on record parameter. return true; } if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value. { Debug.Assert(parent.Parent is { }); switch (parent.Parent.Kind()) { case SyntaxKind.VariableDeclarator: case SyntaxKind.PropertyDeclaration: switch (initializer.Kind) { case BoundKind.Block: var block = (BoundBlock)initializer; if (block.Statements.Length == 1) { initializer = (BoundStatement)block.Statements.First(); if (initializer.Kind == BoundKind.ExpressionStatement) { goto case BoundKind.ExpressionStatement; } } break; case BoundKind.ExpressionStatement: return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator; } break; } } return false; } /// <summary> /// Returns true if the initializer is a field initializer which should be optimized out /// </summary> private static bool ShouldOptimizeOutInitializer(BoundStatement initializer) { BoundStatement statement = initializer; if (statement.Kind != BoundKind.ExpressionStatement) { return false; } BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator; if (assignment == null) { return false; } Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess); var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol; if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType()) { return false; } BoundExpression rhs = assignment.Right; return rhs.IsDefaultValue(); } // There are three situations in which the language permits passing rvalues by reference. // (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind) // // #1: Receiver of a struct/generic method call. // // The language only requires that receivers of method calls must be readable (RValues are ok). // // However the underlying implementation passes receivers of struct methods by reference. // In such situations it may be possible for the call to cause or observe writes to the receiver variable. // As a result it is not valid to replace receiver variable with a reference to it or the other way around. // // Example1: // static int x = 123; // async static Task<string> Test1() // { // // cannot capture "x" by value, since write in M1 is observable // return x.ToString(await M1()); // } // // async static Task<string> M1() // { // x = 42; // await Task.Yield(); // return ""; // } // // Example2: // static int x = 123; // static string Test1() // { // // cannot replace value of "x" with a reference to "x" // // since that would make the method see the mutations in M1(); // return (x + 0).ToString(M1()); // } // // static string M1() // { // x = 42; // return ""; // } // // #2: Ordinary byval argument passed to an "in" parameter. // // The language only requires that ordinary byval arguments must be readable (RValues are ok). // However if the target parameter is an "in" parameter, the underlying implementation passes by reference. // // Example: // static int x = 123; // static void Main(string[] args) // { // // cannot replace value of "x" with a direct reference to x // // since Test will see unexpected changes due to aliasing. // Test(x + 0); // } // // static void Test(in int y) // { // Console.WriteLine(y); // x = 42; // Console.WriteLine(y); // } // // #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type. // // Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type // is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because // there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference. // // Example: // M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluating to the builder // static void M(ref CustomHandler c) { } // // NB: The readonliness is not considered here. // We only care about possible introduction of aliasing. I.E. RValue->LValue change. // Even if we start with a readonly variable, it cannot be lowered into a writeable one, // with one exception - spilling of the value into a local, which is ok. // internal static bool CanBePassedByReference(BoundExpression expr) { if (expr.ConstantValue != null) { return false; } switch (expr.Kind) { case BoundKind.Parameter: case BoundKind.Local: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: case BoundKind.PseudoVariable: case BoundKind.DiscardExpression: return true; case BoundKind.DeconstructValuePlaceholder: // we will consider that placeholder always represents a temp local // the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed return true; case BoundKind.InterpolatedStringArgumentPlaceholder: // An argument placeholder is always a reference to some type of temp local, // either representing a user-typed expression that went through this path // itself when it was originally visited, or the trailing out parameter that // is passed by out. return true; case BoundKind.InterpolatedStringHandlerPlaceholder: // A handler placeholder is the receiver of the interpolated string AppendLiteral // or AppendFormatted calls, and should never be defensively copied. return true; case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (eventAccess.IsUsableAsField) { if (eventAccess.EventSymbol.IsStatic) return true; Debug.Assert(eventAccess.ReceiverOpt is { }); return CanBePassedByReference(eventAccess.ReceiverOpt); } return false; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; if (!fieldAccess.FieldSymbol.IsStatic) { Debug.Assert(fieldAccess.ReceiverOpt is { }); return CanBePassedByReference(fieldAccess.ReceiverOpt); } return true; case BoundKind.Sequence: return CanBePassedByReference(((BoundSequence)expr).Value); case BoundKind.AssignmentOperator: return ((BoundAssignmentOperator)expr).IsRef; case BoundKind.ConditionalOperator: return ((BoundConditionalOperator)expr).IsRef; case BoundKind.Call: return ((BoundCall)expr).Method.RefKind != RefKind.None; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None; case BoundKind.IndexerAccess: return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None; case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var refKind = patternIndexer.PatternSymbol switch { PropertySymbol p => p.RefKind, MethodSymbol m => m.RefKind, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return refKind != RefKind.None; case BoundKind.Conversion: var conversion = ((BoundConversion)expr); return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } }; } return false; } private void CheckRefReadOnlySymbols(MethodSymbol symbol) { if (symbol.ReturnsByRefReadonly || symbol.Parameters.Any(p => p.RefKind == RefKind.In)) { _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists(); } } private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo() { return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); } #if DEBUG /// <summary> /// Note: do not use a static/singleton instance of this type, as it holds state. /// </summary> private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Asserts that no unexpected nodes survived local rewriting. /// </summary> public static void Validate(BoundNode node) { try { new LocalRewritingValidator().Visit(node); } catch (InsufficientExecutionStackException) { // Intentionally ignored to let the overflow get caught in a more crucial visitor } } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { Fail(node); return null; } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { Fail(node); return null; } public override BoundNode? VisitIfStatement(BoundIfStatement node) { Fail(node); return null; } public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { Fail(node); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { Fail(node); return null; } private void Fail(BoundNode node) { Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting"); } } #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard { private readonly CSharpCompilation _compilation; private readonly SyntheticBoundNodeFactory _factory; private readonly SynthesizedSubmissionFields _previousSubmissionFields; private readonly bool _allowOmissionOfConditionalCalls; private LoweredDynamicOperationFactory _dynamicFactory; private bool _sawLambdas; private int _availableLocalFunctionOrdinal; private bool _inExpressionLambda; private bool _sawAwait; private bool _sawAwaitInExceptionHandler; private bool _needsSpilling; private readonly BindingDiagnosticBag _diagnostics; private Instrumenter _instrumenter; private readonly BoundStatement _rootStatement; private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly; private LocalRewriter( CSharpCompilation compilation, MethodSymbol containingMethod, int containingMethodOrdinal, BoundStatement rootStatement, NamedTypeSymbol? containingType, SyntheticBoundNodeFactory factory, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, BindingDiagnosticBag diagnostics, Instrumenter instrumenter) { _compilation = compilation; _factory = factory; _factory.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal); _previousSubmissionFields = previousSubmissionFields; _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls; _diagnostics = diagnostics; Debug.Assert(instrumenter != null); #if DEBUG // Ensure that only expected kinds of instrumenters are in use _ = RemoveDynamicAnalysisInjectors(instrumenter); #endif _instrumenter = instrumenter; _rootStatement = rootStatement; } /// <summary> /// Lower a block of code by performing local rewritings. /// </summary> public static BoundStatement Rewrite( CSharpCompilation compilation, MethodSymbol method, int methodOrdinal, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, bool instrumentForDynamicAnalysis, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, DebugDocumentProvider debugDocumentProvider, BindingDiagnosticBag diagnostics, out bool sawLambdas, out bool sawLocalFunctions, out bool sawAwaitInExceptionHandler) { Debug.Assert(statement != null); Debug.Assert(compilationState != null); try { var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics); DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null; // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not. // Presence of sequence points in the tree affects final IL, therefore, we always generate them. var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics, dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton); statement.CheckLocalsDefined(); var loweredStatement = localRewriter.VisitStatement(statement); Debug.Assert(loweredStatement is { }); loweredStatement.CheckLocalsDefined(); sawLambdas = localRewriter._sawLambdas; sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0; sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler; if (localRewriter._needsSpilling && !loweredStatement.HasErrors) { // Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression. var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics); spilledStatement.CheckLocalsDefined(); loweredStatement = spilledStatement; } if (dynamicInstrumenter != null) { dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans; } #if DEBUG LocalRewritingValidator.Validate(loweredStatement); #endif return loweredStatement; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false; return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true); } } private bool Instrument { get { return !_inExpressionLambda; } } private PEModuleBuilder? EmitModule { get { return _factory.CompilationState.ModuleBuilderOpt; } } /// <summary> /// Return the translated node, or null if no code is necessary in the translation. /// </summary> public override BoundNode? Visit(BoundNode? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); BoundExpression? expr = node as BoundExpression; if (expr != null) { return VisitExpressionImpl(expr); } return node.Accept(this); } [return: NotNullIfNotNull("node")] private BoundExpression? VisitExpression(BoundExpression? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); // https://github.com/dotnet/roslyn/issues/47682 return VisitExpressionImpl(node)!; } private BoundStatement? VisitStatement(BoundStatement? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); return (BoundStatement?)node.Accept(this); } private BoundExpression? VisitExpressionImpl(BoundExpression node) { ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { TypeSymbol? type = node.Type; if (type?.IsNullableType() != true) { return MakeLiteral(node.Syntax, constantValue, type); } } var visited = VisitExpressionWithStackGuard(node); // If you *really* need to change the type, consider using an indirect method // like compound assignment does (extra flag only passed when it is an expression // statement means that this constraint is not violated). // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees. // Unused deconstructions are lowered to produce a return value that isn't a tuple type. Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) || visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || IsUnusedDeconstruction(node)); if (visited != null && visited != node && node.Kind != BoundKind.ImplicitReceiver && node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder) { if (!CanBePassedByReference(node) && CanBePassedByReference(visited)) { visited = RefAccessMustMakeCopy(visited); } } return visited; } private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited) { visited = new BoundPassByCopy( visited.Syntax, visited, type: visited.Type); return visited; } private static bool IsUnusedDeconstruction(BoundExpression node) { return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed; } public override BoundNode VisitLambda(BoundLambda node) { _sawLambdas = true; var lambda = node.Symbol; CheckRefReadOnlySymbols(lambda); var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; try { _factory.CurrentFunction = lambda; if (lambda.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } return base.VisitLambda(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; } } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { int localFunctionOrdinal = _availableLocalFunctionOrdinal++; var localFunction = node.Symbol; CheckRefReadOnlySymbols(localFunction); if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder) { var typeParameters = localFunction.TypeParameters; if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint)) { moduleBuilder.EnsureIsUnmanagedAttributeExists(); } if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) || typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger()))) { moduleBuilder.EnsureNativeIntegerAttributeExists(); } if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction)) { bool constraintsNeedNullableAttribute = typeParameters.Any( typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute()); if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute())) { moduleBuilder.EnsureNullableAttributeExists(); } } static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) => predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate); } var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; var oldDynamicFactory = _dynamicFactory; try { _factory.CurrentFunction = localFunction; if (localFunction.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } if (localFunction.IsGenericMethod) { // Each generic local function gets its own dynamic factory because it // needs its own container to cache dynamic call-sites. That type (the container) "inherits" // local function's type parameters as well as type parameters of all containing methods. _dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal); } return base.VisitLocalFunctionStatement(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; _dynamicFactory = oldDynamicFactory; } } private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter) { switch (instrumenter) { case DynamicAnalysisInjector { Previous: var previous }: return RemoveDynamicAnalysisInjectors(previous); case DebugInfoInjector { Previous: var previous } injector: var newPrevious = RemoveDynamicAnalysisInjectors(previous); if ((object)newPrevious == previous) { return injector; } else if ((object)newPrevious == Instrumenter.NoOp) { return DebugInfoInjector.Singleton; } else { return new DebugInfoInjector(previous); } case CompoundInstrumenter compound: // If we hit this it means a new kind of compound instrumenter is in use. // Either add a new case or add an abstraction that lets us // filter out the unwanted injectors in a more generalized way. throw ExceptionUtilities.UnexpectedValue(compound); default: Debug.Assert((object)instrumenter == Instrumenter.NoOp); return instrumenter; } } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return PlaceholderReplacement(node); } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { if (_inExpressionLambda) { // Expression trees do not include the 'this' argument for members. return node; } return PlaceholderReplacement(node); } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) => PlaceholderReplacement(node); public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) => PlaceholderReplacement(node); /// <summary> /// Returns substitution currently used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is no substitution. /// </summary> private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); var value = _placeholderReplacementMapDoNotUseDirectly[placeholder]; AssertPlaceholderReplacement(placeholder, value); return value; } [Conditional("DEBUG")] private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// Sets substitution used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is already a substitution. /// </summary> private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { AssertPlaceholderReplacement(placeholder, value); if (_placeholderReplacementMapDoNotUseDirectly is null) { _placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>(); } _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value); } /// <summary> /// Removes substitution currently used by the rewriter for a placeholder node. /// Asserts if there isn't already a substitution. /// </summary> private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder); Debug.Assert(removed); } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { // DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children since the BadExpression // may represent being unable to use the child as an lvalue or rvalue. return node; } private static BoundExpression BadExpression(BoundExpression node) { Debug.Assert(node.Type is { }); return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child) { return BadExpression(syntax, resultType, ImmutableArray.Create(child)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2) { return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children) { return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType); } private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol { Debug.Assert((syntax != null) ^ (location != null)); symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location); return symbol is { }; } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember) { return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { MethodSymbol method; if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method)) { return method; } else { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); SpecialType type = (SpecialType)descriptor.DeclaringTypeId; TypeSymbol container = compilation.Assembly.GetSpecialType(type); TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity); return new ErrorMethodSymbol(container, returnType, "Missing"); } } private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method) { return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method); } private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method) { return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method); } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType); Debug.Assert(sourceType is { }); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true); } return node.Update(sourceType, getTypeFromHandle, type); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var operand = this.VisitExpression(node.Operand); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true); } return node.Update(operand, getTypeFromHandle, type); } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { ImmutableArray<BoundStatement> originalStatements = node.Statements; var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length); foreach (var initializer in originalStatements) { if (IsFieldOrPropertyInitializer(initializer)) { if (initializer.Kind == BoundKind.Block) { var block = (BoundBlock)initializer; var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true); Debug.Assert(statement is { }); statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement))); } else { statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true)); } } else { statements.Add(VisitStatement(initializer)); } } int optimizedInitializers = 0; bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; for (int i = 0; i < statements.Count; i++) { var stmt = statements[i]; if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt))) { optimizedInitializers++; if (_factory.CurrentFunction?.IsStatic == false) { // NOTE: Dev11 removes static initializers if ONLY all of them are optimized out statements[i] = null; } } } ImmutableArray<BoundStatement> rewrittenStatements; if (optimizedInitializers == statements.Count) { // all are optimized away rewrittenStatements = ImmutableArray<BoundStatement>.Empty; statements.Free(); } else { // instrument remaining statements int remaining = 0; for (int i = 0; i < statements.Count; i++) { BoundStatement? rewritten = statements[i]; if (rewritten != null) { if (IsFieldOrPropertyInitializer(originalStatements[i])) { BoundStatement original = originalStatements[i]; if (Instrument && !original.WasCompilerGenerated) { rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten); } } statements[remaining] = rewritten; remaining++; } } statements.Count = remaining; // trim any trailing nulls rewrittenStatements = statements.ToImmutableAndFree()!; } return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { // An array access expression can be indexed using any of the following types: // * an integer primitive // * a System.Index // * a System.Range // The last two are only supported on SZArrays. For those cases we need to // lower into the appropriate helper methods. if (node.Indices.Length != 1) { return base.VisitArrayAccess(node)!; } var indexType = VisitType(node.Indices[0].Type); var F = _factory; BoundNode resultExpr; if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { // array[Index] is treated like a pattern-based System.Index indexing // expression, except that array indexers don't actually exist (they // don't have symbols) var arrayLocal = F.StoreToTemp( VisitExpression(node.Expression), out BoundAssignmentOperator arrayAssign); var indexOffsetExpr = MakePatternIndexOffsetExpression( node.Indices[0], F.ArrayLength(arrayLocal), out _); resultExpr = F.Sequence( ImmutableArray.Create(arrayLocal.LocalSymbol), ImmutableArray.Create<BoundExpression>(arrayAssign), F.ArrayAccess( arrayLocal, ImmutableArray.Create(indexOffsetExpr))); } else if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // array[Range] is compiled to: // System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range) Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array }); var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations; resultExpr = F.Call( receiver: null, F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T) .Construct(ImmutableArray.Create(elementType)), ImmutableArray.Create( VisitExpression(node.Expression), VisitExpression(node.Indices[0]))); } else { resultExpr = base.VisitArrayAccess(node)!; } return resultExpr; } internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer) { var syntax = initializer.Syntax; if (syntax.IsKind(SyntaxKind.Parameter)) { // This is an initialization of a generated property based on record parameter. return true; } if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value. { Debug.Assert(parent.Parent is { }); switch (parent.Parent.Kind()) { case SyntaxKind.VariableDeclarator: case SyntaxKind.PropertyDeclaration: switch (initializer.Kind) { case BoundKind.Block: var block = (BoundBlock)initializer; if (block.Statements.Length == 1) { initializer = (BoundStatement)block.Statements.First(); if (initializer.Kind == BoundKind.ExpressionStatement) { goto case BoundKind.ExpressionStatement; } } break; case BoundKind.ExpressionStatement: return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator; } break; } } return false; } /// <summary> /// Returns true if the initializer is a field initializer which should be optimized out /// </summary> private static bool ShouldOptimizeOutInitializer(BoundStatement initializer) { BoundStatement statement = initializer; if (statement.Kind != BoundKind.ExpressionStatement) { return false; } BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator; if (assignment == null) { return false; } Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess); var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol; if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType()) { return false; } BoundExpression rhs = assignment.Right; return rhs.IsDefaultValue(); } // There are three situations in which the language permits passing rvalues by reference. // (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind) // // #1: Receiver of a struct/generic method call. // // The language only requires that receivers of method calls must be readable (RValues are ok). // // However the underlying implementation passes receivers of struct methods by reference. // In such situations it may be possible for the call to cause or observe writes to the receiver variable. // As a result it is not valid to replace receiver variable with a reference to it or the other way around. // // Example1: // static int x = 123; // async static Task<string> Test1() // { // // cannot capture "x" by value, since write in M1 is observable // return x.ToString(await M1()); // } // // async static Task<string> M1() // { // x = 42; // await Task.Yield(); // return ""; // } // // Example2: // static int x = 123; // static string Test1() // { // // cannot replace value of "x" with a reference to "x" // // since that would make the method see the mutations in M1(); // return (x + 0).ToString(M1()); // } // // static string M1() // { // x = 42; // return ""; // } // // #2: Ordinary byval argument passed to an "in" parameter. // // The language only requires that ordinary byval arguments must be readable (RValues are ok). // However if the target parameter is an "in" parameter, the underlying implementation passes by reference. // // Example: // static int x = 123; // static void Main(string[] args) // { // // cannot replace value of "x" with a direct reference to x // // since Test will see unexpected changes due to aliasing. // Test(x + 0); // } // // static void Test(in int y) // { // Console.WriteLine(y); // x = 42; // Console.WriteLine(y); // } // // #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type. // // Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type // is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because // there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference. // // Example: // M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluating to the builder // static void M(ref CustomHandler c) { } // // NB: The readonliness is not considered here. // We only care about possible introduction of aliasing. I.E. RValue->LValue change. // Even if we start with a readonly variable, it cannot be lowered into a writeable one, // with one exception - spilling of the value into a local, which is ok. // internal static bool CanBePassedByReference(BoundExpression expr) { if (expr.ConstantValue != null) { return false; } switch (expr.Kind) { case BoundKind.Parameter: case BoundKind.Local: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: case BoundKind.PseudoVariable: case BoundKind.DiscardExpression: return true; case BoundKind.DeconstructValuePlaceholder: // we will consider that placeholder always represents a temp local // the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed return true; case BoundKind.InterpolatedStringArgumentPlaceholder: // An argument placeholder is always a reference to some type of temp local, // either representing a user-typed expression that went through this path // itself when it was originally visited, or the trailing out parameter that // is passed by out. return true; case BoundKind.InterpolatedStringHandlerPlaceholder: // A handler placeholder is the receiver of the interpolated string AppendLiteral // or AppendFormatted calls, and should never be defensively copied. return true; case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (eventAccess.IsUsableAsField) { if (eventAccess.EventSymbol.IsStatic) return true; Debug.Assert(eventAccess.ReceiverOpt is { }); return CanBePassedByReference(eventAccess.ReceiverOpt); } return false; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; if (!fieldAccess.FieldSymbol.IsStatic) { Debug.Assert(fieldAccess.ReceiverOpt is { }); return CanBePassedByReference(fieldAccess.ReceiverOpt); } return true; case BoundKind.Sequence: return CanBePassedByReference(((BoundSequence)expr).Value); case BoundKind.AssignmentOperator: return ((BoundAssignmentOperator)expr).IsRef; case BoundKind.ConditionalOperator: return ((BoundConditionalOperator)expr).IsRef; case BoundKind.Call: return ((BoundCall)expr).Method.RefKind != RefKind.None; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None; case BoundKind.IndexerAccess: return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None; case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var refKind = patternIndexer.PatternSymbol switch { PropertySymbol p => p.RefKind, MethodSymbol m => m.RefKind, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return refKind != RefKind.None; case BoundKind.Conversion: var conversion = ((BoundConversion)expr); return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } }; } return false; } private void CheckRefReadOnlySymbols(MethodSymbol symbol) { if (symbol.ReturnsByRefReadonly || symbol.Parameters.Any(p => p.RefKind == RefKind.In)) { _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists(); } } private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo() { return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); } #if DEBUG /// <summary> /// Note: do not use a static/singleton instance of this type, as it holds state. /// </summary> private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Asserts that no unexpected nodes survived local rewriting. /// </summary> public static void Validate(BoundNode node) { try { new LocalRewritingValidator().Visit(node); } catch (InsufficientExecutionStackException) { // Intentionally ignored to let the overflow get caught in a more crucial visitor } } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { Fail(node); return null; } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { Fail(node); return null; } public override BoundNode? VisitIfStatement(BoundIfStatement node) { Fail(node); return null; } public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { Fail(node); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { Fail(node); return null; } private void Fail(BoundNode node) { Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting"); } } #endif } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Internal/GoToDefinition/FSharpFindDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared] internal class FSharpFindDefinitionService : IFindDefinitionService { private readonly IFSharpFindDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpFindDefinitionService(IFSharpFindDefinitionService service) { _service = service; } public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared] internal class FSharpFindDefinitionService : IFindDefinitionService { private readonly IFSharpFindDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpFindDefinitionService(IFSharpFindDefinitionService service) { _service = service; } public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x)); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Symbols/PublicModel/AliasSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class AliasSymbol : Symbol, IAliasSymbol { private readonly Symbols.AliasSymbol _underlying; public AliasSymbol(Symbols.AliasSymbol underlying) { RoslynDebug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceOrTypeSymbol IAliasSymbol.Target { get { return _underlying.Target.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitAlias(this); } protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default { return visitor.VisitAlias(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class AliasSymbol : Symbol, IAliasSymbol { private readonly Symbols.AliasSymbol _underlying; public AliasSymbol(Symbols.AliasSymbol underlying) { RoslynDebug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceOrTypeSymbol IAliasSymbol.Target { get { return _underlying.Target.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitAlias(this); } protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default { return visitor.VisitAlias(this); } #endregion } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Helpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Helpers { public const uint LLF_SEARCH_EXPAND_MEMBERS = 0x0400; public const uint LLF_SEARCH_WITH_EXPANSION = 0x0800; public const uint LLT_PROJREF = (uint)_LIB_LISTTYPE.LLT_INTERFACEUSEDBYCLASSES; public static ObjectListKind ListTypeToObjectListKind(uint listType) { switch (listType) { case (uint)_LIB_LISTTYPE.LLT_CLASSES: return ObjectListKind.Types; case (uint)_LIB_LISTTYPE.LLT_HIERARCHY: return ObjectListKind.Hierarchy; case (uint)_LIB_LISTTYPE.LLT_MEMBERS: return ObjectListKind.Members; case (uint)_LIB_LISTTYPE.LLT_NAMESPACES: return ObjectListKind.Namespaces; case (uint)_LIB_LISTTYPE.LLT_PACKAGE: return ObjectListKind.Projects; case LLT_PROJREF: return ObjectListKind.References; case (uint)_LIB_LISTTYPE.LLT_USESCLASSES: return ObjectListKind.BaseTypes; } Debug.Fail("Unsupported list type: " + ((_LIB_LISTTYPE)listType).ToString()); return ObjectListKind.None; } public static uint ObjectListKindToListType(ObjectListKind kind) { switch (kind) { case ObjectListKind.BaseTypes: return (uint)_LIB_LISTTYPE.LLT_USESCLASSES; case ObjectListKind.Hierarchy: return (uint)_LIB_LISTTYPE.LLT_HIERARCHY; case ObjectListKind.Members: return (uint)_LIB_LISTTYPE.LLT_MEMBERS; case ObjectListKind.Namespaces: return (uint)_LIB_LISTTYPE.LLT_NAMESPACES; case ObjectListKind.Projects: return (uint)_LIB_LISTTYPE.LLT_PACKAGE; case ObjectListKind.References: return LLT_PROJREF; case ObjectListKind.Types: return (uint)_LIB_LISTTYPE.LLT_CLASSES; } Debug.Fail("Unsupported object list kind: " + kind.ToString()); return 0; } public const _LIB_LISTFLAGS ClassView = _LIB_LISTFLAGS.LLF_TRUENESTING; public static bool IsClassView(uint flags) => (flags & (uint)_LIB_LISTFLAGS.LLF_TRUENESTING) != 0; public static bool IsFindSymbol(uint flags) => (flags & (uint)_LIB_LISTFLAGS.LLF_USESEARCHFILTER) != 0; internal static bool IsObjectBrowser(uint flags) => (flags & ((uint)_LIB_LISTFLAGS.LLF_TRUENESTING | (uint)_LIB_LISTFLAGS.LLF_USESEARCHFILTER | (uint)_LIB_LISTFLAGS.LLF_RESOURCEVIEW)) == 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Helpers { public const uint LLF_SEARCH_EXPAND_MEMBERS = 0x0400; public const uint LLF_SEARCH_WITH_EXPANSION = 0x0800; public const uint LLT_PROJREF = (uint)_LIB_LISTTYPE.LLT_INTERFACEUSEDBYCLASSES; public static ObjectListKind ListTypeToObjectListKind(uint listType) { switch (listType) { case (uint)_LIB_LISTTYPE.LLT_CLASSES: return ObjectListKind.Types; case (uint)_LIB_LISTTYPE.LLT_HIERARCHY: return ObjectListKind.Hierarchy; case (uint)_LIB_LISTTYPE.LLT_MEMBERS: return ObjectListKind.Members; case (uint)_LIB_LISTTYPE.LLT_NAMESPACES: return ObjectListKind.Namespaces; case (uint)_LIB_LISTTYPE.LLT_PACKAGE: return ObjectListKind.Projects; case LLT_PROJREF: return ObjectListKind.References; case (uint)_LIB_LISTTYPE.LLT_USESCLASSES: return ObjectListKind.BaseTypes; } Debug.Fail("Unsupported list type: " + ((_LIB_LISTTYPE)listType).ToString()); return ObjectListKind.None; } public static uint ObjectListKindToListType(ObjectListKind kind) { switch (kind) { case ObjectListKind.BaseTypes: return (uint)_LIB_LISTTYPE.LLT_USESCLASSES; case ObjectListKind.Hierarchy: return (uint)_LIB_LISTTYPE.LLT_HIERARCHY; case ObjectListKind.Members: return (uint)_LIB_LISTTYPE.LLT_MEMBERS; case ObjectListKind.Namespaces: return (uint)_LIB_LISTTYPE.LLT_NAMESPACES; case ObjectListKind.Projects: return (uint)_LIB_LISTTYPE.LLT_PACKAGE; case ObjectListKind.References: return LLT_PROJREF; case ObjectListKind.Types: return (uint)_LIB_LISTTYPE.LLT_CLASSES; } Debug.Fail("Unsupported object list kind: " + kind.ToString()); return 0; } public const _LIB_LISTFLAGS ClassView = _LIB_LISTFLAGS.LLF_TRUENESTING; public static bool IsClassView(uint flags) => (flags & (uint)_LIB_LISTFLAGS.LLF_TRUENESTING) != 0; public static bool IsFindSymbol(uint flags) => (flags & (uint)_LIB_LISTFLAGS.LLF_USESEARCHFILTER) != 0; internal static bool IsObjectBrowser(uint flags) => (flags & ((uint)_LIB_LISTFLAGS.LLF_TRUENESTING | (uint)_LIB_LISTFLAGS.LLF_USESEARCHFILTER | (uint)_LIB_LISTFLAGS.LLF_RESOURCEVIEW)) == 0; } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/RQName/RQName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Features.RQName; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// Helpers related to <see cref="RQName"/>s. The resulting strings are suitable to pass as the pszRQName /// arguments to methods in <see cref="IVsRefactorNotify"/> and <see cref="IVsSymbolicNavigationNotify"/>. /// </summary> public static class RQName { /// <summary> /// Returns an RQName for the given symbol, or <see langword="null"/> if the symbol cannot be represented by an RQName. /// </summary> /// <param name="symbol">The symbol to build an RQName for.</param> /// <returns>A string suitable to pass as the pszRQName argument to methods in <see cref="IVsRefactorNotify"/> /// and <see cref="IVsSymbolicNavigationNotify"/>.</returns> public static string? From(ISymbol symbol) => RQNameInternal.From(symbol); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Features.RQName; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// Helpers related to <see cref="RQName"/>s. The resulting strings are suitable to pass as the pszRQName /// arguments to methods in <see cref="IVsRefactorNotify"/> and <see cref="IVsSymbolicNavigationNotify"/>. /// </summary> public static class RQName { /// <summary> /// Returns an RQName for the given symbol, or <see langword="null"/> if the symbol cannot be represented by an RQName. /// </summary> /// <param name="symbol">The symbol to build an RQName for.</param> /// <returns>A string suitable to pass as the pszRQName argument to methods in <see cref="IVsRefactorNotify"/> /// and <see cref="IVsSymbolicNavigationNotify"/>.</returns> public static string? From(ISymbol symbol) => RQNameInternal.From(symbol); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/TableDataSource/VisualStudioBaseDiagnosticListTable.LiveTableDataSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Common; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract partial class VisualStudioBaseDiagnosticListTable { /// <summary> /// Error list diagnostic source for "Build + Intellisense" setting. /// See <see cref="VisualStudioDiagnosticListTableWorkspaceEventListener.VisualStudioDiagnosticListTable.BuildTableDataSource"/> /// for error list diagnostic source for "Build only" setting. /// </summary> protected class LiveTableDataSource : AbstractRoslynTableDataSource<DiagnosticTableItem, DiagnosticsUpdatedArgs> { private readonly string _identifier; private readonly IDiagnosticService _diagnosticService; private readonly Workspace _workspace; private readonly OpenDocumentTracker<DiagnosticTableItem> _tracker; /// <summary> /// Flag indicating if a build inside Visual Studio is in progress. /// We get build progress updates from <see cref="ExternalErrorDiagnosticUpdateSource.BuildProgressChanged"/>. /// Build progress events are guaranteed to be invoked in a serial fashion during build. /// </summary> private bool _isBuildRunning; public LiveTableDataSource(Workspace workspace, IDiagnosticService diagnosticService, string identifier, ExternalErrorDiagnosticUpdateSource? buildUpdateSource = null) : base(workspace) { _workspace = workspace; _identifier = identifier; _tracker = new OpenDocumentTracker<DiagnosticTableItem>(_workspace); _diagnosticService = diagnosticService; ConnectToDiagnosticService(workspace, diagnosticService); ConnectToBuildUpdateSource(buildUpdateSource); } public override string DisplayName => ServicesVSResources.CSharp_VB_Diagnostics_Table_Data_Source; public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource; public override string Identifier => _identifier; public override object GetItemKey(DiagnosticsUpdatedArgs data) => data.Id; private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource? buildUpdateSource) { if (buildUpdateSource == null) { // it can be null in unit test return; } OnBuildProgressChanged(buildUpdateSource.IsInProgress); buildUpdateSource.BuildProgressChanged += (_, progress) => OnBuildProgressChanged(running: progress != ExternalErrorDiagnosticUpdateSource.BuildProgress.Done); } private void OnBuildProgressChanged(bool running) { _isBuildRunning = running; // We mark error list "Build + Intellisense" setting as stable, // i.e. shown as "Error List" without the trailing "...", if both the following are true: // 1. User invoked build is not running inside Visual Studio AND // 2. Solution crawler is not running in background to compute intellisense diagnostics. ChangeStableStateIfRequired(newIsStable: !_isBuildRunning && !IsSolutionCrawlerRunning); } public override AbstractTableEntriesSnapshot<DiagnosticTableItem> CreateSnapshot( AbstractTableEntriesSource<DiagnosticTableItem> source, int version, ImmutableArray<DiagnosticTableItem> items, ImmutableArray<ITrackingPoint> trackingPoints) { var diagnosticSource = (DiagnosticTableEntriesSource)source; var snapshot = new TableEntriesSnapshot(diagnosticSource, version, items, trackingPoints); if (diagnosticSource.SupportSpanTracking && !trackingPoints.IsDefaultOrEmpty) { // track the open document so that we can throw away tracking points on document close properly _tracker.TrackOpenDocument(diagnosticSource.TrackingDocumentId, diagnosticSource.Key, snapshot); } return snapshot; } protected override object GetOrUpdateAggregationKey(DiagnosticsUpdatedArgs data) { var key = TryGetAggregateKey(data); if (key == null) { key = CreateAggregationKey(data); AddAggregateKey(data, key); return key; } if (!CheckAggregateKey(key as AggregatedKey, data as DiagnosticsUpdatedArgs)) { RemoveStaledData(data); key = CreateAggregationKey(data); AddAggregateKey(data, key); } return key; } private bool CheckAggregateKey(AggregatedKey? key, DiagnosticsUpdatedArgs? args) { if (key == null) { return true; } if (args?.DocumentId == null || args?.Solution == null) { return true; } var documents = GetDocumentsWithSameFilePath(args.Solution, args.DocumentId); return key.DocumentIds == documents; } private object CreateAggregationKey(DiagnosticsUpdatedArgs data) { if (data.DocumentId == null || data.Solution == null) return GetItemKey(data); if (data.Id is not LiveDiagnosticUpdateArgsId liveArgsId) return GetItemKey(data); var documents = GetDocumentsWithSameFilePath(data.Solution, data.DocumentId); return new AggregatedKey(documents, liveArgsId.Analyzer, liveArgsId.Kind); } private void PopulateInitialData(Workspace workspace, IDiagnosticService diagnosticService) { var diagnostics = diagnosticService.GetPushDiagnosticBuckets( workspace, projectId: null, documentId: null, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken: CancellationToken.None); foreach (var bucket in diagnostics) { // We only need to issue an event to VS that these docs have diagnostics associated with them. So // we create a dummy notification for this. It doesn't matter that it is 'DiagnosticsRemoved' as // this doesn't actually change any data. All that will happen now is that VS will call back into // us for these IDs and we'll fetch the diagnostics at that point. OnDataAddedOrChanged(DiagnosticsUpdatedArgs.DiagnosticsRemoved( bucket.Id, bucket.Workspace, solution: null, bucket.ProjectId, bucket.DocumentId)); } } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { using (Logger.LogBlock(FunctionId.LiveTableDataSource_OnDiagnosticsUpdated, a => GetDiagnosticUpdatedMessage(_workspace, a), e, CancellationToken.None)) { if (_workspace != e.Workspace) { return; } var diagnostics = e.GetPushDiagnostics(_workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); if (diagnostics.Length == 0) { OnDataRemoved(e); return; } var count = diagnostics.Where(ShouldInclude).Count(); if (count <= 0) { OnDataRemoved(e); return; } OnDataAddedOrChanged(e); } } public override AbstractTableEntriesSource<DiagnosticTableItem> CreateTableEntriesSource(object data) { var item = (UpdatedEventArgs)data; return new TableEntriesSource(this, item.Workspace, item.ProjectId, item.DocumentId, item.Id); } private void ConnectToDiagnosticService(Workspace workspace, IDiagnosticService diagnosticService) { if (diagnosticService == null) { // it can be null in unit test return; } _diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; PopulateInitialData(workspace, diagnosticService); } private static bool ShouldInclude(DiagnosticData diagnostic) { if (diagnostic == null) { // guard us from wrong provider that gives null diagnostic Debug.Assert(false, "Let's see who does this"); return false; } // If this diagnostic is for LSP only, then we won't show it here if (diagnostic.Properties.ContainsKey(nameof(DocumentPropertiesService.DiagnosticsLspClientName))) { return false; } switch (diagnostic.Severity) { case DiagnosticSeverity.Info: case DiagnosticSeverity.Warning: case DiagnosticSeverity.Error: return true; case DiagnosticSeverity.Hidden: default: return false; } } public override IEqualityComparer<DiagnosticTableItem> GroupingComparer => DiagnosticTableItem.GroupingComparer.Instance; public override IEnumerable<DiagnosticTableItem> Order(IEnumerable<DiagnosticTableItem> groupedItems) { // this should make order of result always deterministic. we only need these 6 values since data with // all these same will merged to one. return groupedItems.OrderBy(d => d.Data.DataLocation?.OriginalStartLine ?? 0) .ThenBy(d => d.Data.DataLocation?.OriginalStartColumn ?? 0) .ThenBy(d => d.Data.Id) .ThenBy(d => d.Data.Message) .ThenBy(d => d.Data.DataLocation?.OriginalEndLine ?? 0) .ThenBy(d => d.Data.DataLocation?.OriginalEndColumn ?? 0); } private class TableEntriesSource : DiagnosticTableEntriesSource { private readonly LiveTableDataSource _source; private readonly Workspace _workspace; private readonly ProjectId? _projectId; private readonly DocumentId? _documentId; private readonly object _id; private readonly string _buildTool; public TableEntriesSource(LiveTableDataSource source, Workspace workspace, ProjectId? projectId, DocumentId? documentId, object id) { _source = source; _workspace = workspace; _projectId = projectId; _documentId = documentId; _id = id; _buildTool = (id as BuildToolId)?.BuildTool ?? string.Empty; } public override object Key => _id; public override string BuildTool => _buildTool; public override bool SupportSpanTracking => _documentId != null; public override DocumentId? TrackingDocumentId => _documentId; public override ImmutableArray<DiagnosticTableItem> GetItems() { var provider = _source._diagnosticService; var items = provider.GetPushDiagnosticsAsync(_workspace, _projectId, _documentId, _id, includeSuppressedDiagnostics: true, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken: CancellationToken.None) .AsTask() .WaitAndGetResult_CanCallOnBackground(CancellationToken.None) .Where(ShouldInclude) .Select(data => DiagnosticTableItem.Create(_workspace, data)); return items.ToImmutableArray(); } public override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticTableItem> items) => _workspace.CreateTrackingPoints(_documentId, items); } private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticTableItem>, IWpfTableEntriesSnapshot { private readonly DiagnosticTableEntriesSource _source; private FrameworkElement[]? _descriptions; public TableEntriesSnapshot( DiagnosticTableEntriesSource source, int version, ImmutableArray<DiagnosticTableItem> items, ImmutableArray<ITrackingPoint> trackingPoints) : base(version, items, trackingPoints) { _source = source; } public override bool TryGetValue(int index, string columnName, [NotNullWhen(returnValue: true)] out object? content) { // REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async? // also, what is cancellation mechanism? var item = GetItem(index); if (item == null) { content = null; return false; } var data = item.Data; switch (columnName) { case StandardTableKeyNames.ErrorRank: content = ValueTypeCache.GetOrCreate(GetErrorRank(data)); return content != null; case StandardTableKeyNames.ErrorSeverity: content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity)); return content != null; case StandardTableKeyNames.ErrorCode: content = data.Id; return content != null; case StandardTableKeyNames.ErrorCodeToolTip: content = BrowserHelper.GetHelpLinkToolTip(data); return content != null; case StandardTableKeyNames.HelpKeyword: content = data.Id; return content != null; case StandardTableKeyNames.HelpLink: content = BrowserHelper.GetHelpLink(data)?.AbsoluteUri; return content != null; case StandardTableKeyNames.ErrorCategory: content = data.Category; return content != null; case StandardTableKeyNames.ErrorSource: content = ValueTypeCache.GetOrCreate(GetErrorSource(_source.BuildTool)); return content != null; case StandardTableKeyNames.BuildTool: content = GetBuildTool(_source.BuildTool); return content != null; case StandardTableKeyNames.Text: content = data.Message; return content != null; case StandardTableKeyNames.DocumentName: content = data.DataLocation?.GetFilePath(); return content != null; case StandardTableKeyNames.Line: content = data.DataLocation?.MappedStartLine ?? 0; return true; case StandardTableKeyNames.Column: content = data.DataLocation?.MappedStartColumn ?? 0; return true; case StandardTableKeyNames.ProjectName: content = item.ProjectName; return content != null; case ProjectNames: var names = item.ProjectNames; content = names; return names.Length > 0; case StandardTableKeyNames.ProjectGuid: content = ValueTypeCache.GetOrCreate(item.ProjectGuid); return (Guid)content != Guid.Empty; case ProjectGuids: var guids = item.ProjectGuids; content = guids; return guids.Length > 0; case StandardTableKeyNames.SuppressionState: content = data.IsSuppressed ? SuppressionState.Suppressed : SuppressionState.Active; return true; default: content = null; return false; } } private string GetBuildTool(string buildTool) { // for build tool, regardless where error is coming from ("build" or "live"), // we show "compiler" to users. if (buildTool == PredefinedBuildTools.Live) { return PredefinedBuildTools.Build; } return _source.BuildTool; } private ErrorSource GetErrorSource(string buildTool) { if (buildTool == PredefinedBuildTools.Build) { return ErrorSource.Build; } return ErrorSource.Other; } private ErrorRank GetErrorRank(DiagnosticData item) { if (!item.Properties.TryGetValue(WellKnownDiagnosticPropertyNames.Origin, out var value)) { return ErrorRank.Other; } switch (value) { case WellKnownDiagnosticTags.Build: // any error from build gets lowest priority // see https://github.com/dotnet/roslyn/issues/28807 // // this is only used when intellisense (live) errors are involved. // with "build only" filter on, we use order of errors came in from build for ordering // and doesn't use ErrorRank for ordering (by giving same rank for all errors) // // when live errors are involved, by default, error list will use the following to sort errors // error rank > project rank > project name > file name > line > column // which will basically make syntax errors show up before declaration error and method body semantic errors // among same type of errors, leaf project's error will show up first and then projects that depends on the leaf projects // // any build errors mixed with live errors will show up at the end. when live errors are on, some of errors // still left as build errors such as errors produced after CompilationStages.Compile or ones listed here // http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/CSharpCompilerDiagnosticAnalyzer.cs,23 or similar ones for VB // and etc. return ErrorRank.PostBuild; case nameof(ErrorRank.Lexical): return ErrorRank.Lexical; case nameof(ErrorRank.Syntactic): return ErrorRank.Syntactic; case nameof(ErrorRank.Declaration): return ErrorRank.Declaration; case nameof(ErrorRank.Semantic): return ErrorRank.Semantic; case nameof(ErrorRank.Emit): return ErrorRank.Emit; case nameof(ErrorRank.PostBuild): return ErrorRank.PostBuild; default: return ErrorRank.Other; } } public override bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken) => TryNavigateToItem(index, previewTab, activate, cancellationToken); #region IWpfTableEntriesSnapshot public bool CanCreateDetailsContent(int index) { var item = GetItem(index)?.Data; if (item == null) { return false; } return !string.IsNullOrWhiteSpace(item.Description); } public bool TryCreateDetailsContent(int index, [NotNullWhen(returnValue: true)] out FrameworkElement? expandedContent) { var item = GetItem(index)?.Data; if (item == null) { expandedContent = null; return false; } expandedContent = GetOrCreateTextBlock(ref _descriptions, this.Count, index, item, i => GetDescriptionTextBlock(i)); return true; } public bool TryCreateDetailsStringContent(int index, [NotNullWhen(returnValue: true)] out string? content) { var item = GetItem(index)?.Data; if (item == null) { content = null; return false; } if (string.IsNullOrWhiteSpace(item.Description)) { content = null; return false; } content = item.Description; return content != null; } private static FrameworkElement GetDescriptionTextBlock(DiagnosticData item) { return new TextBlock() { Background = null, Padding = new Thickness(10, 6, 10, 8), TextWrapping = TextWrapping.Wrap, Text = item.Description }; } private static FrameworkElement GetOrCreateTextBlock( [NotNull] ref FrameworkElement[]? caches, int count, int index, DiagnosticData item, Func<DiagnosticData, FrameworkElement> elementCreator) { if (caches == null) { caches = new FrameworkElement[count]; } if (caches[index] == null) { caches[index] = elementCreator(item); } return caches[index]; } // unused ones public bool TryCreateColumnContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out FrameworkElement? content) { content = null; return false; } public bool TryCreateImageContent(int index, string columnName, bool singleColumnView, out ImageMoniker content) { content = default; return false; } public bool TryCreateStringContent(int index, string columnName, bool truncatedText, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content) { content = null; return false; } public bool TryCreateToolTip(int index, string columnName, [NotNullWhen(returnValue: true)] out object? toolTip) { toolTip = null; return false; } #pragma warning disable IDE0060 // Remove unused parameter - TODO: remove this once we moved to new drop public bool TryCreateStringContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content) #pragma warning restore IDE0060 // Remove unused parameter { content = null; return false; } #endregion } private static string GetDiagnosticUpdatedMessage(Workspace workspace, DiagnosticsUpdatedArgs e) { var id = e.Id.ToString(); if (e.Id is LiveDiagnosticUpdateArgsId live) { id = $"{live.Analyzer.ToString()}/{live.Kind}"; } else if (e.Id is AnalyzerUpdateArgsId analyzer) { id = analyzer.Analyzer.ToString(); } var diagnostics = e.GetPushDiagnostics(workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); return $"Kind:{e.Workspace.Kind}, Analyzer:{id}, Update:{e.Kind}, {(object?)e.DocumentId ?? e.ProjectId}, ({string.Join(Environment.NewLine, diagnostics)})"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Common; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract partial class VisualStudioBaseDiagnosticListTable { /// <summary> /// Error list diagnostic source for "Build + Intellisense" setting. /// See <see cref="VisualStudioDiagnosticListTableWorkspaceEventListener.VisualStudioDiagnosticListTable.BuildTableDataSource"/> /// for error list diagnostic source for "Build only" setting. /// </summary> protected class LiveTableDataSource : AbstractRoslynTableDataSource<DiagnosticTableItem, DiagnosticsUpdatedArgs> { private readonly string _identifier; private readonly IDiagnosticService _diagnosticService; private readonly Workspace _workspace; private readonly OpenDocumentTracker<DiagnosticTableItem> _tracker; /// <summary> /// Flag indicating if a build inside Visual Studio is in progress. /// We get build progress updates from <see cref="ExternalErrorDiagnosticUpdateSource.BuildProgressChanged"/>. /// Build progress events are guaranteed to be invoked in a serial fashion during build. /// </summary> private bool _isBuildRunning; public LiveTableDataSource(Workspace workspace, IDiagnosticService diagnosticService, string identifier, ExternalErrorDiagnosticUpdateSource? buildUpdateSource = null) : base(workspace) { _workspace = workspace; _identifier = identifier; _tracker = new OpenDocumentTracker<DiagnosticTableItem>(_workspace); _diagnosticService = diagnosticService; ConnectToDiagnosticService(workspace, diagnosticService); ConnectToBuildUpdateSource(buildUpdateSource); } public override string DisplayName => ServicesVSResources.CSharp_VB_Diagnostics_Table_Data_Source; public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource; public override string Identifier => _identifier; public override object GetItemKey(DiagnosticsUpdatedArgs data) => data.Id; private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource? buildUpdateSource) { if (buildUpdateSource == null) { // it can be null in unit test return; } OnBuildProgressChanged(buildUpdateSource.IsInProgress); buildUpdateSource.BuildProgressChanged += (_, progress) => OnBuildProgressChanged(running: progress != ExternalErrorDiagnosticUpdateSource.BuildProgress.Done); } private void OnBuildProgressChanged(bool running) { _isBuildRunning = running; // We mark error list "Build + Intellisense" setting as stable, // i.e. shown as "Error List" without the trailing "...", if both the following are true: // 1. User invoked build is not running inside Visual Studio AND // 2. Solution crawler is not running in background to compute intellisense diagnostics. ChangeStableStateIfRequired(newIsStable: !_isBuildRunning && !IsSolutionCrawlerRunning); } public override AbstractTableEntriesSnapshot<DiagnosticTableItem> CreateSnapshot( AbstractTableEntriesSource<DiagnosticTableItem> source, int version, ImmutableArray<DiagnosticTableItem> items, ImmutableArray<ITrackingPoint> trackingPoints) { var diagnosticSource = (DiagnosticTableEntriesSource)source; var snapshot = new TableEntriesSnapshot(diagnosticSource, version, items, trackingPoints); if (diagnosticSource.SupportSpanTracking && !trackingPoints.IsDefaultOrEmpty) { // track the open document so that we can throw away tracking points on document close properly _tracker.TrackOpenDocument(diagnosticSource.TrackingDocumentId, diagnosticSource.Key, snapshot); } return snapshot; } protected override object GetOrUpdateAggregationKey(DiagnosticsUpdatedArgs data) { var key = TryGetAggregateKey(data); if (key == null) { key = CreateAggregationKey(data); AddAggregateKey(data, key); return key; } if (!CheckAggregateKey(key as AggregatedKey, data as DiagnosticsUpdatedArgs)) { RemoveStaledData(data); key = CreateAggregationKey(data); AddAggregateKey(data, key); } return key; } private bool CheckAggregateKey(AggregatedKey? key, DiagnosticsUpdatedArgs? args) { if (key == null) { return true; } if (args?.DocumentId == null || args?.Solution == null) { return true; } var documents = GetDocumentsWithSameFilePath(args.Solution, args.DocumentId); return key.DocumentIds == documents; } private object CreateAggregationKey(DiagnosticsUpdatedArgs data) { if (data.DocumentId == null || data.Solution == null) return GetItemKey(data); if (data.Id is not LiveDiagnosticUpdateArgsId liveArgsId) return GetItemKey(data); var documents = GetDocumentsWithSameFilePath(data.Solution, data.DocumentId); return new AggregatedKey(documents, liveArgsId.Analyzer, liveArgsId.Kind); } private void PopulateInitialData(Workspace workspace, IDiagnosticService diagnosticService) { var diagnostics = diagnosticService.GetPushDiagnosticBuckets( workspace, projectId: null, documentId: null, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken: CancellationToken.None); foreach (var bucket in diagnostics) { // We only need to issue an event to VS that these docs have diagnostics associated with them. So // we create a dummy notification for this. It doesn't matter that it is 'DiagnosticsRemoved' as // this doesn't actually change any data. All that will happen now is that VS will call back into // us for these IDs and we'll fetch the diagnostics at that point. OnDataAddedOrChanged(DiagnosticsUpdatedArgs.DiagnosticsRemoved( bucket.Id, bucket.Workspace, solution: null, bucket.ProjectId, bucket.DocumentId)); } } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { using (Logger.LogBlock(FunctionId.LiveTableDataSource_OnDiagnosticsUpdated, a => GetDiagnosticUpdatedMessage(_workspace, a), e, CancellationToken.None)) { if (_workspace != e.Workspace) { return; } var diagnostics = e.GetPushDiagnostics(_workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); if (diagnostics.Length == 0) { OnDataRemoved(e); return; } var count = diagnostics.Where(ShouldInclude).Count(); if (count <= 0) { OnDataRemoved(e); return; } OnDataAddedOrChanged(e); } } public override AbstractTableEntriesSource<DiagnosticTableItem> CreateTableEntriesSource(object data) { var item = (UpdatedEventArgs)data; return new TableEntriesSource(this, item.Workspace, item.ProjectId, item.DocumentId, item.Id); } private void ConnectToDiagnosticService(Workspace workspace, IDiagnosticService diagnosticService) { if (diagnosticService == null) { // it can be null in unit test return; } _diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; PopulateInitialData(workspace, diagnosticService); } private static bool ShouldInclude(DiagnosticData diagnostic) { if (diagnostic == null) { // guard us from wrong provider that gives null diagnostic Debug.Assert(false, "Let's see who does this"); return false; } // If this diagnostic is for LSP only, then we won't show it here if (diagnostic.Properties.ContainsKey(nameof(DocumentPropertiesService.DiagnosticsLspClientName))) { return false; } switch (diagnostic.Severity) { case DiagnosticSeverity.Info: case DiagnosticSeverity.Warning: case DiagnosticSeverity.Error: return true; case DiagnosticSeverity.Hidden: default: return false; } } public override IEqualityComparer<DiagnosticTableItem> GroupingComparer => DiagnosticTableItem.GroupingComparer.Instance; public override IEnumerable<DiagnosticTableItem> Order(IEnumerable<DiagnosticTableItem> groupedItems) { // this should make order of result always deterministic. we only need these 6 values since data with // all these same will merged to one. return groupedItems.OrderBy(d => d.Data.DataLocation?.OriginalStartLine ?? 0) .ThenBy(d => d.Data.DataLocation?.OriginalStartColumn ?? 0) .ThenBy(d => d.Data.Id) .ThenBy(d => d.Data.Message) .ThenBy(d => d.Data.DataLocation?.OriginalEndLine ?? 0) .ThenBy(d => d.Data.DataLocation?.OriginalEndColumn ?? 0); } private class TableEntriesSource : DiagnosticTableEntriesSource { private readonly LiveTableDataSource _source; private readonly Workspace _workspace; private readonly ProjectId? _projectId; private readonly DocumentId? _documentId; private readonly object _id; private readonly string _buildTool; public TableEntriesSource(LiveTableDataSource source, Workspace workspace, ProjectId? projectId, DocumentId? documentId, object id) { _source = source; _workspace = workspace; _projectId = projectId; _documentId = documentId; _id = id; _buildTool = (id as BuildToolId)?.BuildTool ?? string.Empty; } public override object Key => _id; public override string BuildTool => _buildTool; public override bool SupportSpanTracking => _documentId != null; public override DocumentId? TrackingDocumentId => _documentId; public override ImmutableArray<DiagnosticTableItem> GetItems() { var provider = _source._diagnosticService; var items = provider.GetPushDiagnosticsAsync(_workspace, _projectId, _documentId, _id, includeSuppressedDiagnostics: true, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken: CancellationToken.None) .AsTask() .WaitAndGetResult_CanCallOnBackground(CancellationToken.None) .Where(ShouldInclude) .Select(data => DiagnosticTableItem.Create(_workspace, data)); return items.ToImmutableArray(); } public override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticTableItem> items) => _workspace.CreateTrackingPoints(_documentId, items); } private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticTableItem>, IWpfTableEntriesSnapshot { private readonly DiagnosticTableEntriesSource _source; private FrameworkElement[]? _descriptions; public TableEntriesSnapshot( DiagnosticTableEntriesSource source, int version, ImmutableArray<DiagnosticTableItem> items, ImmutableArray<ITrackingPoint> trackingPoints) : base(version, items, trackingPoints) { _source = source; } public override bool TryGetValue(int index, string columnName, [NotNullWhen(returnValue: true)] out object? content) { // REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async? // also, what is cancellation mechanism? var item = GetItem(index); if (item == null) { content = null; return false; } var data = item.Data; switch (columnName) { case StandardTableKeyNames.ErrorRank: content = ValueTypeCache.GetOrCreate(GetErrorRank(data)); return content != null; case StandardTableKeyNames.ErrorSeverity: content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity)); return content != null; case StandardTableKeyNames.ErrorCode: content = data.Id; return content != null; case StandardTableKeyNames.ErrorCodeToolTip: content = BrowserHelper.GetHelpLinkToolTip(data); return content != null; case StandardTableKeyNames.HelpKeyword: content = data.Id; return content != null; case StandardTableKeyNames.HelpLink: content = BrowserHelper.GetHelpLink(data)?.AbsoluteUri; return content != null; case StandardTableKeyNames.ErrorCategory: content = data.Category; return content != null; case StandardTableKeyNames.ErrorSource: content = ValueTypeCache.GetOrCreate(GetErrorSource(_source.BuildTool)); return content != null; case StandardTableKeyNames.BuildTool: content = GetBuildTool(_source.BuildTool); return content != null; case StandardTableKeyNames.Text: content = data.Message; return content != null; case StandardTableKeyNames.DocumentName: content = data.DataLocation?.GetFilePath(); return content != null; case StandardTableKeyNames.Line: content = data.DataLocation?.MappedStartLine ?? 0; return true; case StandardTableKeyNames.Column: content = data.DataLocation?.MappedStartColumn ?? 0; return true; case StandardTableKeyNames.ProjectName: content = item.ProjectName; return content != null; case ProjectNames: var names = item.ProjectNames; content = names; return names.Length > 0; case StandardTableKeyNames.ProjectGuid: content = ValueTypeCache.GetOrCreate(item.ProjectGuid); return (Guid)content != Guid.Empty; case ProjectGuids: var guids = item.ProjectGuids; content = guids; return guids.Length > 0; case StandardTableKeyNames.SuppressionState: content = data.IsSuppressed ? SuppressionState.Suppressed : SuppressionState.Active; return true; default: content = null; return false; } } private string GetBuildTool(string buildTool) { // for build tool, regardless where error is coming from ("build" or "live"), // we show "compiler" to users. if (buildTool == PredefinedBuildTools.Live) { return PredefinedBuildTools.Build; } return _source.BuildTool; } private ErrorSource GetErrorSource(string buildTool) { if (buildTool == PredefinedBuildTools.Build) { return ErrorSource.Build; } return ErrorSource.Other; } private ErrorRank GetErrorRank(DiagnosticData item) { if (!item.Properties.TryGetValue(WellKnownDiagnosticPropertyNames.Origin, out var value)) { return ErrorRank.Other; } switch (value) { case WellKnownDiagnosticTags.Build: // any error from build gets lowest priority // see https://github.com/dotnet/roslyn/issues/28807 // // this is only used when intellisense (live) errors are involved. // with "build only" filter on, we use order of errors came in from build for ordering // and doesn't use ErrorRank for ordering (by giving same rank for all errors) // // when live errors are involved, by default, error list will use the following to sort errors // error rank > project rank > project name > file name > line > column // which will basically make syntax errors show up before declaration error and method body semantic errors // among same type of errors, leaf project's error will show up first and then projects that depends on the leaf projects // // any build errors mixed with live errors will show up at the end. when live errors are on, some of errors // still left as build errors such as errors produced after CompilationStages.Compile or ones listed here // http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/CSharpCompilerDiagnosticAnalyzer.cs,23 or similar ones for VB // and etc. return ErrorRank.PostBuild; case nameof(ErrorRank.Lexical): return ErrorRank.Lexical; case nameof(ErrorRank.Syntactic): return ErrorRank.Syntactic; case nameof(ErrorRank.Declaration): return ErrorRank.Declaration; case nameof(ErrorRank.Semantic): return ErrorRank.Semantic; case nameof(ErrorRank.Emit): return ErrorRank.Emit; case nameof(ErrorRank.PostBuild): return ErrorRank.PostBuild; default: return ErrorRank.Other; } } public override bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken) => TryNavigateToItem(index, previewTab, activate, cancellationToken); #region IWpfTableEntriesSnapshot public bool CanCreateDetailsContent(int index) { var item = GetItem(index)?.Data; if (item == null) { return false; } return !string.IsNullOrWhiteSpace(item.Description); } public bool TryCreateDetailsContent(int index, [NotNullWhen(returnValue: true)] out FrameworkElement? expandedContent) { var item = GetItem(index)?.Data; if (item == null) { expandedContent = null; return false; } expandedContent = GetOrCreateTextBlock(ref _descriptions, this.Count, index, item, i => GetDescriptionTextBlock(i)); return true; } public bool TryCreateDetailsStringContent(int index, [NotNullWhen(returnValue: true)] out string? content) { var item = GetItem(index)?.Data; if (item == null) { content = null; return false; } if (string.IsNullOrWhiteSpace(item.Description)) { content = null; return false; } content = item.Description; return content != null; } private static FrameworkElement GetDescriptionTextBlock(DiagnosticData item) { return new TextBlock() { Background = null, Padding = new Thickness(10, 6, 10, 8), TextWrapping = TextWrapping.Wrap, Text = item.Description }; } private static FrameworkElement GetOrCreateTextBlock( [NotNull] ref FrameworkElement[]? caches, int count, int index, DiagnosticData item, Func<DiagnosticData, FrameworkElement> elementCreator) { if (caches == null) { caches = new FrameworkElement[count]; } if (caches[index] == null) { caches[index] = elementCreator(item); } return caches[index]; } // unused ones public bool TryCreateColumnContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out FrameworkElement? content) { content = null; return false; } public bool TryCreateImageContent(int index, string columnName, bool singleColumnView, out ImageMoniker content) { content = default; return false; } public bool TryCreateStringContent(int index, string columnName, bool truncatedText, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content) { content = null; return false; } public bool TryCreateToolTip(int index, string columnName, [NotNullWhen(returnValue: true)] out object? toolTip) { toolTip = null; return false; } #pragma warning disable IDE0060 // Remove unused parameter - TODO: remove this once we moved to new drop public bool TryCreateStringContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content) #pragma warning restore IDE0060 // Remove unused parameter { content = null; return false; } #endregion } private static string GetDiagnosticUpdatedMessage(Workspace workspace, DiagnosticsUpdatedArgs e) { var id = e.Id.ToString(); if (e.Id is LiveDiagnosticUpdateArgsId live) { id = $"{live.Analyzer.ToString()}/{live.Kind}"; } else if (e.Id is AnalyzerUpdateArgsId analyzer) { id = analyzer.Analyzer.ToString(); } var diagnostics = e.GetPushDiagnostics(workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); return $"Kind:{e.Workspace.Kind}, Analyzer:{id}, Update:{e.Kind}, {(object?)e.DocumentId ?? e.ProjectId}, ({string.Join(Environment.NewLine, diagnostics)})"; } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { return syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinConflictMarker(position, cancellationToken) || syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) || syntaxTree.IsInInactiveRegion(position, cancellationToken); } public static bool IsInInactiveRegion( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); // cases: // $ is EOF // #if false // | // #if false // |$ // #if false // | // #if false // |$ if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken)) { return false; } // The latter two are the hard cases we don't actually have an // DisabledTextTrivia yet. var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return true; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return false; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return false; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken; } } } } return false; } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out _, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { genericIdentifier = default; lessThanToken = default; var index = 0; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() == SyntaxKind.None) { return false; } // check whether we are under type or member decl if (token.GetAncestor<TypeParameterListSyntax>() != null) { return false; } var stack = 0; while (true) { switch (token.Kind()) { case SyntaxKind.LessThanToken: if (stack == 0) { // got here so we read successfully up to a < now we have to read the // name before that and we're done! lessThanToken = token; token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } // ok // so we've read something like: // ~~~~~~~~~<a,b,... // but we need to know the simple name that precedes the < // it could be // ~~~~~~goo<a,b,... if (token.Kind() == SyntaxKind.IdentifierToken) { // okay now check whether it is actually partially written if (IsFullyWrittenGeneric(token, lessThanToken)) { return false; } genericIdentifier = token; return true; } return false; } else { stack--; break; } case SyntaxKind.GreaterThanGreaterThanToken: stack++; goto case SyntaxKind.GreaterThanToken; // fall through case SyntaxKind.GreaterThanToken: stack++; break; case SyntaxKind.AsteriskToken: // for int* case SyntaxKind.QuestionToken: // for int? case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :) case SyntaxKind.ColonColonToken: // for global:: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.IdentifierToken: break; case SyntaxKind.CommaToken: if (stack == 0) { index++; } break; default: // user might have typed "in" on the way to typing "int" // don't want to disregard this genericname because of that if (SyntaxFacts.IsKeywordKind(token.Kind())) { break; } // anything else and we're sunk. return false; } // look backward one token, include skipped tokens, because the parser frequently // does skip them in cases like: "Func<A, B", which get parsed as: expression // statement "Func<A" with missing semicolon, expression statement "B" with missing // semicolon, and the "," is skipped. token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } } } private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken) { return token.Parent is GenericNameSyntax genericName && genericName.TypeArgumentList != null && genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { return syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinConflictMarker(position, cancellationToken) || syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) || syntaxTree.IsInInactiveRegion(position, cancellationToken); } public static bool IsInInactiveRegion( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); // cases: // $ is EOF // #if false // | // #if false // |$ // #if false // | // #if false // |$ if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken)) { return false; } // The latter two are the hard cases we don't actually have an // DisabledTextTrivia yet. var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return true; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return false; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return false; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken; } } } } return false; } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out _, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { genericIdentifier = default; lessThanToken = default; var index = 0; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() == SyntaxKind.None) { return false; } // check whether we are under type or member decl if (token.GetAncestor<TypeParameterListSyntax>() != null) { return false; } var stack = 0; while (true) { switch (token.Kind()) { case SyntaxKind.LessThanToken: if (stack == 0) { // got here so we read successfully up to a < now we have to read the // name before that and we're done! lessThanToken = token; token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } // ok // so we've read something like: // ~~~~~~~~~<a,b,... // but we need to know the simple name that precedes the < // it could be // ~~~~~~goo<a,b,... if (token.Kind() == SyntaxKind.IdentifierToken) { // okay now check whether it is actually partially written if (IsFullyWrittenGeneric(token, lessThanToken)) { return false; } genericIdentifier = token; return true; } return false; } else { stack--; break; } case SyntaxKind.GreaterThanGreaterThanToken: stack++; goto case SyntaxKind.GreaterThanToken; // fall through case SyntaxKind.GreaterThanToken: stack++; break; case SyntaxKind.AsteriskToken: // for int* case SyntaxKind.QuestionToken: // for int? case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :) case SyntaxKind.ColonColonToken: // for global:: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.IdentifierToken: break; case SyntaxKind.CommaToken: if (stack == 0) { index++; } break; default: // user might have typed "in" on the way to typing "int" // don't want to disregard this genericname because of that if (SyntaxFacts.IsKeywordKind(token.Kind())) { break; } // anything else and we're sunk. return false; } // look backward one token, include skipped tokens, because the parser frequently // does skip them in cases like: "Func<A, B", which get parsed as: expression // statement "Func<A" with missing semicolon, expression statement "B" with missing // semicolon, and the "," is skipped. token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } } } private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken) { return token.Parent is GenericNameSyntax genericName && genericName.TypeArgumentList != null && genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/IDebuggerTextView.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor { internal interface IDebuggerTextView { bool IsImmediateWindow { get; } uint StartBufferUpdate(); void EndBufferUpdate(uint cookie); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor { internal interface IDebuggerTextView { bool IsImmediateWindow { get; } uint StartBufferUpdate(); void EndBufferUpdate(uint cookie); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AliasSymbolCache.cs
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Shared.Utilities { using TreeMap = ConcurrentDictionary<(SyntaxTree tree, int namespaceId), ImmutableDictionary<INamespaceOrTypeSymbol, IAliasSymbol>>; internal static class AliasSymbolCache { // NOTE : I chose to cache on compilation assuming this cache will be quite small. usually number of times alias is used is quite small. // but if that turns out not true, we can move this cache to be based on semantic model. unlike compilation that would be cached // in compilation cache in certain host (VS), semantic model comes and goes more frequently which will release cache more often. private static readonly ConditionalWeakTable<Compilation, TreeMap> s_treeAliasMap = new(); private static readonly ConditionalWeakTable<Compilation, TreeMap>.CreateValueCallback s_createTreeMap = c => new TreeMap(); public static bool TryGetAliasSymbol(SemanticModel semanticModel, int namespaceId, INamespaceOrTypeSymbol targetSymbol, out IAliasSymbol? aliasSymbol) { // TODO: given semantic model must be not speculative semantic model for now. // currently it can't be checked since it is not exposed to common layer yet. // once exposed, this method itself will make sure it use original semantic model aliasSymbol = null; if (!s_treeAliasMap.TryGetValue(semanticModel.Compilation, out var treeMap) || !treeMap.TryGetValue((semanticModel.SyntaxTree, namespaceId), out var symbolMap)) { return false; } symbolMap.TryGetValue(targetSymbol, out aliasSymbol); return true; } public static void AddAliasSymbols(SemanticModel semanticModel, int namespaceId, IEnumerable<IAliasSymbol> aliasSymbols) { // given semantic model must be the original semantic model for now var treeMap = s_treeAliasMap.GetValue(semanticModel.Compilation, s_createTreeMap); // check again to see whether somebody has beaten us var key = (tree: semanticModel.SyntaxTree, namespaceId); if (treeMap.ContainsKey(key)) { return; } var builder = ImmutableDictionary.CreateBuilder<INamespaceOrTypeSymbol, IAliasSymbol>(); foreach (var alias in aliasSymbols) { if (builder.ContainsKey(alias.Target)) { continue; } // only put the first one. builder.Add(alias.Target, alias); } // Use namespace id rather than holding onto namespace node directly, that will keep the tree alive as long as // the compilation is alive. In the current design, a node can come and go even if compilation is alive through recoverable tree. treeMap.TryAdd(key, builder.ToImmutable()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Shared.Utilities { using TreeMap = ConcurrentDictionary<(SyntaxTree tree, int namespaceId), ImmutableDictionary<INamespaceOrTypeSymbol, IAliasSymbol>>; internal static class AliasSymbolCache { // NOTE : I chose to cache on compilation assuming this cache will be quite small. usually number of times alias is used is quite small. // but if that turns out not true, we can move this cache to be based on semantic model. unlike compilation that would be cached // in compilation cache in certain host (VS), semantic model comes and goes more frequently which will release cache more often. private static readonly ConditionalWeakTable<Compilation, TreeMap> s_treeAliasMap = new(); private static readonly ConditionalWeakTable<Compilation, TreeMap>.CreateValueCallback s_createTreeMap = c => new TreeMap(); public static bool TryGetAliasSymbol(SemanticModel semanticModel, int namespaceId, INamespaceOrTypeSymbol targetSymbol, out IAliasSymbol? aliasSymbol) { // TODO: given semantic model must be not speculative semantic model for now. // currently it can't be checked since it is not exposed to common layer yet. // once exposed, this method itself will make sure it use original semantic model aliasSymbol = null; if (!s_treeAliasMap.TryGetValue(semanticModel.Compilation, out var treeMap) || !treeMap.TryGetValue((semanticModel.SyntaxTree, namespaceId), out var symbolMap)) { return false; } symbolMap.TryGetValue(targetSymbol, out aliasSymbol); return true; } public static void AddAliasSymbols(SemanticModel semanticModel, int namespaceId, IEnumerable<IAliasSymbol> aliasSymbols) { // given semantic model must be the original semantic model for now var treeMap = s_treeAliasMap.GetValue(semanticModel.Compilation, s_createTreeMap); // check again to see whether somebody has beaten us var key = (tree: semanticModel.SyntaxTree, namespaceId); if (treeMap.ContainsKey(key)) { return; } var builder = ImmutableDictionary.CreateBuilder<INamespaceOrTypeSymbol, IAliasSymbol>(); foreach (var alias in aliasSymbols) { if (builder.ContainsKey(alias.Target)) { continue; } // only put the first one. builder.Add(alias.Target, alias); } // Use namespace id rather than holding onto namespace node directly, that will keep the tree alive as long as // the compilation is alive. In the current design, a node can come and go even if compilation is alive through recoverable tree. treeMap.TryAdd(key, builder.ToImmutable()); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/UseConditionalExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/DocumentationComments/DocumentationCommentOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.DocumentationComments { internal static class DocumentationCommentOptions { public static readonly PerLanguageOption2<bool> AutoXmlDocCommentGeneration = new(nameof(DocumentationCommentOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, storageLocation: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation")); } [ExportOptionProvider, Shared] internal sealed class DocumentationCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(DocumentationCommentOptions.AutoXmlDocCommentGeneration); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.DocumentationComments { internal static class DocumentationCommentOptions { public static readonly PerLanguageOption2<bool> AutoXmlDocCommentGeneration = new(nameof(DocumentationCommentOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, storageLocation: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation")); } [ExportOptionProvider, Shared] internal sealed class DocumentationCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(DocumentationCommentOptions.AutoXmlDocCommentGeneration); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/ValueTracking/BindableTextBlock.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class BindableTextBlock : TextBlock { public IList<Inline> InlineCollection { get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBlock = (BindableTextBlock)sender; var newList = (IList<Inline>)e.NewValue; textBlock.Inlines.Clear(); foreach (var inline in newList) { textBlock.Inlines.Add(inline); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class BindableTextBlock : TextBlock { public IList<Inline> InlineCollection { get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBlock = (BindableTextBlock)sender; var newList = (IList<Inline>)e.NewValue; textBlock.Inlines.Clear(); foreach (var inline in newList) { textBlock.Inlines.Add(inline); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Internal/Diagnostics/FSharpSimplifyNameDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics { [Shared] [ExportLanguageService(typeof(FSharpSimplifyNameDiagnosticAnalyzerService), LanguageNames.FSharp)] internal class FSharpSimplifyNameDiagnosticAnalyzerService : ILanguageService { private readonly IFSharpSimplifyNameDiagnosticAnalyzer _analyzer; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpSimplifyNameDiagnosticAnalyzerService(IFSharpSimplifyNameDiagnosticAnalyzer analyzer) { _analyzer = analyzer; } public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken) { return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken); } } [DiagnosticAnalyzer(LanguageNames.FSharp)] internal class FSharpSimplifyNameDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor( IDEDiagnosticIds.SimplifyNamesDiagnosticId, ExternalAccessFSharpResources.SimplifyName, ExternalAccessFSharpResources.NameCanBeSimplified, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public override int Priority => 100; // Default = 50 public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var analyzer = document.Project.LanguageServices.GetService<FSharpSimplifyNameDiagnosticAnalyzerService>(); if (analyzer == null) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken); } public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } public bool OpenFileOnly(OptionSet options) { return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics { [Shared] [ExportLanguageService(typeof(FSharpSimplifyNameDiagnosticAnalyzerService), LanguageNames.FSharp)] internal class FSharpSimplifyNameDiagnosticAnalyzerService : ILanguageService { private readonly IFSharpSimplifyNameDiagnosticAnalyzer _analyzer; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpSimplifyNameDiagnosticAnalyzerService(IFSharpSimplifyNameDiagnosticAnalyzer analyzer) { _analyzer = analyzer; } public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken) { return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken); } } [DiagnosticAnalyzer(LanguageNames.FSharp)] internal class FSharpSimplifyNameDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor( IDEDiagnosticIds.SimplifyNamesDiagnosticId, ExternalAccessFSharpResources.SimplifyName, ExternalAccessFSharpResources.NameCanBeSimplified, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public override int Priority => 100; // Default = 50 public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var analyzer = document.Project.LanguageServices.GetService<FSharpSimplifyNameDiagnosticAnalyzerService>(); if (analyzer == null) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken); } public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } public bool OpenFileOnly(OptionSet options) { return true; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Helper type to map <see cref="IDEDiagnosticIds"/> to an unique editorconfig code style option, if any, /// such that diagnostic's severity can be configured in .editorconfig with an entry such as: /// "%option_name% = %option_value%:%severity% /// </summary> internal static class IDEDiagnosticIdToOptionMappingHelper { private static readonly ConcurrentDictionary<string, ImmutableHashSet<IOption2>> s_diagnosticIdToOptionMap = new(); private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, ImmutableHashSet<IOption2>>> s_diagnosticIdToLanguageSpecificOptionsMap = new(); public static bool TryGetMappedOptions(string diagnosticId, string language, [NotNullWhen(true)] out ImmutableHashSet<IOption2>? options) => s_diagnosticIdToOptionMap.TryGetValue(diagnosticId, out options) || (s_diagnosticIdToLanguageSpecificOptionsMap.TryGetValue(language, out var map) && map.TryGetValue(diagnosticId, out options)); public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> perLanguageOptions) { diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId)); perLanguageOptions = perLanguageOptions ?? throw new ArgumentNullException(nameof(perLanguageOptions)); var options = perLanguageOptions.Cast<IOption2>().ToImmutableHashSet(); AddOptionMapping(s_diagnosticIdToOptionMap, diagnosticId, options); } public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> languageSpecificOptions, string language) { diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId)); languageSpecificOptions = languageSpecificOptions ?? throw new ArgumentNullException(nameof(languageSpecificOptions)); language = language ?? throw new ArgumentNullException(nameof(language)); var map = s_diagnosticIdToLanguageSpecificOptionsMap.GetOrAdd(language, _ => new ConcurrentDictionary<string, ImmutableHashSet<IOption2>>()); var options = languageSpecificOptions.Cast<IOption2>().ToImmutableHashSet(); AddOptionMapping(map, diagnosticId, options); } private static void AddOptionMapping(ConcurrentDictionary<string, ImmutableHashSet<IOption2>> map, string diagnosticId, ImmutableHashSet<IOption2> options) { // Verify that the option is either being added for the first time, or the existing option is already the same. // Latter can happen in tests as we re-instantiate the analyzer for every test, which attempts to add the mapping every time. Debug.Assert(!map.TryGetValue(diagnosticId, out var existingOptions) || options.SetEquals(existingOptions)); map.TryAdd(diagnosticId, options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Helper type to map <see cref="IDEDiagnosticIds"/> to an unique editorconfig code style option, if any, /// such that diagnostic's severity can be configured in .editorconfig with an entry such as: /// "%option_name% = %option_value%:%severity% /// </summary> internal static class IDEDiagnosticIdToOptionMappingHelper { private static readonly ConcurrentDictionary<string, ImmutableHashSet<IOption2>> s_diagnosticIdToOptionMap = new(); private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, ImmutableHashSet<IOption2>>> s_diagnosticIdToLanguageSpecificOptionsMap = new(); public static bool TryGetMappedOptions(string diagnosticId, string language, [NotNullWhen(true)] out ImmutableHashSet<IOption2>? options) => s_diagnosticIdToOptionMap.TryGetValue(diagnosticId, out options) || (s_diagnosticIdToLanguageSpecificOptionsMap.TryGetValue(language, out var map) && map.TryGetValue(diagnosticId, out options)); public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> perLanguageOptions) { diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId)); perLanguageOptions = perLanguageOptions ?? throw new ArgumentNullException(nameof(perLanguageOptions)); var options = perLanguageOptions.Cast<IOption2>().ToImmutableHashSet(); AddOptionMapping(s_diagnosticIdToOptionMap, diagnosticId, options); } public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> languageSpecificOptions, string language) { diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId)); languageSpecificOptions = languageSpecificOptions ?? throw new ArgumentNullException(nameof(languageSpecificOptions)); language = language ?? throw new ArgumentNullException(nameof(language)); var map = s_diagnosticIdToLanguageSpecificOptionsMap.GetOrAdd(language, _ => new ConcurrentDictionary<string, ImmutableHashSet<IOption2>>()); var options = languageSpecificOptions.Cast<IOption2>().ToImmutableHashSet(); AddOptionMapping(map, diagnosticId, options); } private static void AddOptionMapping(ConcurrentDictionary<string, ImmutableHashSet<IOption2>> map, string diagnosticId, ImmutableHashSet<IOption2> options) { // Verify that the option is either being added for the first time, or the existing option is already the same. // Latter can happen in tests as we re-instantiate the analyzer for every test, which attempts to add the mapping every time. Debug.Assert(!map.TryGetValue(diagnosticId, out var existingOptions) || options.SetEquals(existingOptions)); map.TryAdd(diagnosticId, options); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/ConvertForEachToFor/AbstractConvertForEachToForCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertForEachToFor { internal abstract class AbstractConvertForEachToForCodeRefactoringProvider< TStatementSyntax, TForEachStatement> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TForEachStatement : TStatementSyntax { private const string get_Count = nameof(get_Count); private const string get_Item = nameof(get_Item); private const string Length = nameof(Array.Length); private const string Count = nameof(IList.Count); private static readonly ImmutableArray<string> s_KnownInterfaceNames = ImmutableArray.Create(typeof(IList<>).FullName!, typeof(IReadOnlyList<>).FullName!, typeof(IList).FullName!); protected bool IsForEachVariableWrittenInside { get; private set; } protected abstract string Title { get; } protected abstract bool ValidLocation(ForEachInfo foreachInfo); protected abstract (SyntaxNode start, SyntaxNode end) GetForEachBody(TForEachStatement foreachStatement); protected abstract void ConvertToForStatement( SemanticModel model, ForEachInfo info, SyntaxEditor editor, CancellationToken cancellationToken); protected abstract bool IsValid(TForEachStatement foreachNode); /// <summary> /// Perform language specific checks if the conversion is supported. /// C#: Currently nothing blocking a conversion /// VB: Nested foreach loops sharing a single Next statement, Next statements with multiple variables and next statements /// not using the loop variable are not supported. /// </summary> protected abstract bool IsSupported(ILocalSymbol foreachVariable, IForEachLoopOperation forEachOperation, TForEachStatement foreachStatement); protected static SyntaxAnnotation CreateWarningAnnotation() => WarningAnnotation.Create(FeaturesResources.Warning_colon_semantics_may_change_when_converting_statement); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var foreachStatement = await context.TryGetRelevantNodeAsync<TForEachStatement>().ConfigureAwait(false); if (foreachStatement == null || !IsValid(foreachStatement)) { return; } var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticFact = document.GetRequiredLanguageService<ISemanticFactsService>(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var foreachInfo = GetForeachInfo(semanticFact, model, foreachStatement, cancellationToken); if (foreachInfo == null || !ValidLocation(foreachInfo)) { return; } context.RegisterRefactoring( new ForEachToForCodeAction( Title, c => ConvertForeachToForAsync(document, foreachInfo, c)), foreachStatement.Span); } protected static SyntaxToken CreateUniqueName( ISemanticFactsService semanticFacts, SemanticModel model, SyntaxNode location, string baseName, CancellationToken cancellationToken) => semanticFacts.GenerateUniqueLocalName(model, location, containerOpt: null, baseName, cancellationToken); protected static SyntaxNode GetCollectionVariableName( SemanticModel model, SyntaxGenerator generator, ForEachInfo foreachInfo, SyntaxNode foreachCollectionExpression, CancellationToken cancellationToken) { if (foreachInfo.RequireCollectionStatement) { return generator.IdentifierName( CreateUniqueName(foreachInfo.SemanticFacts, model, foreachInfo.ForEachStatement, foreachInfo.CollectionNameSuggestion, cancellationToken)); } return foreachCollectionExpression.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation); } protected static void IntroduceCollectionStatement( ForEachInfo foreachInfo, SyntaxEditor editor, SyntaxNode type, SyntaxNode foreachCollectionExpression, SyntaxNode collectionVariable) { if (!foreachInfo.RequireCollectionStatement) { return; } // TODO: refactor introduce variable refactoring to real service and use that service here to introduce local variable var generator = editor.Generator; // attach rename annotation to control variable var collectionVariableToken = generator.Identifier(collectionVariable.ToString()).WithAdditionalAnnotations(RenameAnnotation.Create()); // this expression is from user code. don't simplify this. var expression = foreachCollectionExpression.WithoutAnnotations(SimplificationHelpers.DontSimplifyAnnotation); var collectionStatement = generator.LocalDeclarationStatement( type, collectionVariableToken, foreachInfo.RequireExplicitCastInterface ? generator.CastExpression(foreachInfo.ExplicitCastInterface, expression) : expression); // attach trivia to right place collectionStatement = collectionStatement.WithLeadingTrivia(foreachInfo.ForEachStatement.GetFirstToken().LeadingTrivia); editor.InsertBefore(foreachInfo.ForEachStatement, collectionStatement); } protected static TStatementSyntax AddItemVariableDeclaration( SyntaxGenerator generator, SyntaxNode type, SyntaxToken foreachVariable, ITypeSymbol castType, SyntaxNode collectionVariable, SyntaxToken indexVariable) { var memberAccess = generator.ElementAccessExpression( collectionVariable, generator.IdentifierName(indexVariable)); if (castType != null) { memberAccess = generator.CastExpression(castType, memberAccess); } var localDecl = generator.LocalDeclarationStatement( type, foreachVariable, memberAccess); return (TStatementSyntax)localDecl.WithAdditionalAnnotations(Formatter.Annotation); } private ForEachInfo? GetForeachInfo( ISemanticFactsService semanticFact, SemanticModel model, TForEachStatement foreachStatement, CancellationToken cancellationToken) { if (model.GetOperation(foreachStatement, cancellationToken) is not IForEachLoopOperation operation || operation.Locals.Length != 1) { return null; } var foreachVariable = operation.Locals[0]; if (foreachVariable == null) { return null; } // Perform language specific checks if the foreachStatement // is using unsupported features if (!IsSupported(foreachVariable, operation, foreachStatement)) { return null; } IsForEachVariableWrittenInside = CheckIfForEachVariableIsWrittenInside(model, foreachVariable, foreachStatement); var foreachCollection = RemoveImplicitConversion(operation.Collection); if (foreachCollection == null) { return null; } GetInterfaceInfo(model, foreachVariable, foreachCollection, out var explicitCastInterface, out var collectionNameSuggestion, out var countName); if (collectionNameSuggestion == null || countName == null) { return null; } var requireCollectionStatement = CheckRequireCollectionStatement(foreachCollection); return new ForEachInfo( semanticFact, collectionNameSuggestion, countName, explicitCastInterface, foreachVariable.Type, requireCollectionStatement, foreachStatement); } private static void GetInterfaceInfo( SemanticModel model, ILocalSymbol foreachVariable, IOperation foreachCollection, out ITypeSymbol? explicitCastInterface, out string? collectionNameSuggestion, out string? countName) { explicitCastInterface = null; collectionNameSuggestion = null; countName = null; // go through list of types and interfaces to find out right set; var foreachType = foreachVariable.Type; if (IsNullOrErrorType(foreachType)) { return; } var collectionType = foreachCollection.Type; if (IsNullOrErrorType(collectionType)) { return; } // go through explicit types first. // check array case if (collectionType is IArrayTypeSymbol array) { if (array.Rank != 1) { // array type supports IList and other interfaces, but implementation // only supports Rank == 1 case. other case, it will throw on runtime // even if there is no error on compile time. // we explicitly mark that we only support Rank == 1 case return; } if (!IsExchangable(array.ElementType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "array"; explicitCastInterface = null; countName = Length; return; } // check string case if (collectionType.SpecialType == SpecialType.System_String) { var charType = model.Compilation.GetSpecialType(SpecialType.System_Char); if (!IsExchangable(charType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "str"; explicitCastInterface = null; countName = Length; return; } // check ImmutableArray case if (collectionType.OriginalDefinition.Equals(model.Compilation.GetTypeByMetadataName(typeof(ImmutableArray<>).FullName!))) { var indexer = GetInterfaceMember(collectionType, get_Item); if (indexer != null) { if (!IsExchangable(indexer.ReturnType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "array"; explicitCastInterface = null; countName = Length; return; } } // go through all known interfaces we support next. var knownCollectionInterfaces = s_KnownInterfaceNames.Select( s => model.Compilation.GetTypeByMetadataName(s)).Where(t => !IsNullOrErrorType(t)); // for all interfaces, we suggest collection name as "list" collectionNameSuggestion = "list"; // check type itself is interface case if (collectionType.TypeKind == TypeKind.Interface && knownCollectionInterfaces.Contains(collectionType.OriginalDefinition)) { var indexer = GetInterfaceMember(collectionType, get_Item); if (indexer != null && IsExchangable(indexer.ReturnType, foreachType, model.Compilation)) { explicitCastInterface = null; countName = Count; return; } } // check regular cases (implicitly implemented) ITypeSymbol? explicitInterface = null; foreach (var current in collectionType.AllInterfaces) { if (!knownCollectionInterfaces.Contains(current.OriginalDefinition)) { continue; } // see how the type implements the interface var countSymbol = GetInterfaceMember(current, get_Count); var indexerSymbol = GetInterfaceMember(current, get_Item); if (countSymbol == null || indexerSymbol == null) { continue; } if (collectionType.FindImplementationForInterfaceMember(countSymbol) is not IMethodSymbol countImpl || collectionType.FindImplementationForInterfaceMember(indexerSymbol) is not IMethodSymbol indexerImpl) { continue; } if (!IsExchangable(indexerImpl.ReturnType, foreachType, model.Compilation)) { continue; } // implicitly implemented! if (countImpl.ExplicitInterfaceImplementations.IsEmpty && indexerImpl.ExplicitInterfaceImplementations.IsEmpty) { explicitCastInterface = null; countName = Count; return; } if (explicitInterface == null) { explicitInterface = current; } } // okay, we don't have implicitly implemented one, but we do have explicitly implemented one if (explicitInterface != null) { explicitCastInterface = explicitInterface; countName = Count; } } private static bool IsExchangable( ITypeSymbol type1, ITypeSymbol type2, Compilation compilation) { return compilation.HasImplicitConversion(type1, type2) || compilation.HasImplicitConversion(type2, type1); } private static bool IsNullOrErrorType([NotNullWhen(false)] ITypeSymbol? type) => type is null or IErrorTypeSymbol; private static IMethodSymbol? GetInterfaceMember(ITypeSymbol interfaceType, string memberName) { foreach (var current in interfaceType.GetAllInterfacesIncludingThis()) { var members = current.GetMembers(memberName); if (!members.IsEmpty && members[0] is IMethodSymbol method) { return method; } } return null; } private static bool CheckRequireCollectionStatement(IOperation operation) { // this lists type of references in collection part of foreach we will use // as it is in // var element = reference[indexer]; // // otherwise, we will introduce local variable for the expression first and then // do "foreach to for" refactoring // // foreach(var a in new int[] {....}) // to // var array = new int[] { ... } // foreach(var a in array) switch (operation.Kind) { case OperationKind.LocalReference: case OperationKind.FieldReference: case OperationKind.ParameterReference: case OperationKind.PropertyReference: case OperationKind.ArrayElementReference: return false; default: return true; } } private IOperation RemoveImplicitConversion(IOperation collection) { return (collection is IConversionOperation conversion && conversion.IsImplicit) ? RemoveImplicitConversion(conversion.Operand) : collection; } private bool CheckIfForEachVariableIsWrittenInside(SemanticModel semanticModel, ISymbol foreachVariable, TForEachStatement foreachStatement) { var (start, end) = GetForEachBody(foreachStatement); if (start == null || end == null) { // empty body. this can happen in VB return false; } var dataFlow = semanticModel.AnalyzeDataFlow(start, end); if (!dataFlow.Succeeded) { // if we can't get good analysis, assume it is written return true; } return dataFlow.WrittenInside.Contains(foreachVariable); } private async Task<Document> ConvertForeachToForAsync( Document document, ForEachInfo foreachInfo, CancellationToken cancellationToken) { var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var workspace = document.Project.Solution.Workspace; var editor = new SyntaxEditor(model.SyntaxTree.GetRoot(cancellationToken), workspace); ConvertToForStatement(model, foreachInfo, editor, cancellationToken); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } protected class ForEachInfo { public ForEachInfo( ISemanticFactsService semanticFacts, string collectionNameSuggestion, string countName, ITypeSymbol? explicitCastInterface, ITypeSymbol forEachElementType, bool requireCollectionStatement, TForEachStatement forEachStatement) { SemanticFacts = semanticFacts; RequireExplicitCastInterface = explicitCastInterface != null; CollectionNameSuggestion = collectionNameSuggestion; CountName = countName; ExplicitCastInterface = explicitCastInterface; ForEachElementType = forEachElementType; RequireCollectionStatement = requireCollectionStatement || (explicitCastInterface != null); ForEachStatement = forEachStatement; } public ISemanticFactsService SemanticFacts { get; } public bool RequireExplicitCastInterface { get; } public string CollectionNameSuggestion { get; } public string CountName { get; } public ITypeSymbol? ExplicitCastInterface { get; } public ITypeSymbol ForEachElementType { get; } public bool RequireCollectionStatement { get; } public TForEachStatement ForEachStatement { get; } } private class ForEachToForCodeAction : CodeAction.DocumentChangeAction { public ForEachToForCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertForEachToFor { internal abstract class AbstractConvertForEachToForCodeRefactoringProvider< TStatementSyntax, TForEachStatement> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TForEachStatement : TStatementSyntax { private const string get_Count = nameof(get_Count); private const string get_Item = nameof(get_Item); private const string Length = nameof(Array.Length); private const string Count = nameof(IList.Count); private static readonly ImmutableArray<string> s_KnownInterfaceNames = ImmutableArray.Create(typeof(IList<>).FullName!, typeof(IReadOnlyList<>).FullName!, typeof(IList).FullName!); protected bool IsForEachVariableWrittenInside { get; private set; } protected abstract string Title { get; } protected abstract bool ValidLocation(ForEachInfo foreachInfo); protected abstract (SyntaxNode start, SyntaxNode end) GetForEachBody(TForEachStatement foreachStatement); protected abstract void ConvertToForStatement( SemanticModel model, ForEachInfo info, SyntaxEditor editor, CancellationToken cancellationToken); protected abstract bool IsValid(TForEachStatement foreachNode); /// <summary> /// Perform language specific checks if the conversion is supported. /// C#: Currently nothing blocking a conversion /// VB: Nested foreach loops sharing a single Next statement, Next statements with multiple variables and next statements /// not using the loop variable are not supported. /// </summary> protected abstract bool IsSupported(ILocalSymbol foreachVariable, IForEachLoopOperation forEachOperation, TForEachStatement foreachStatement); protected static SyntaxAnnotation CreateWarningAnnotation() => WarningAnnotation.Create(FeaturesResources.Warning_colon_semantics_may_change_when_converting_statement); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var foreachStatement = await context.TryGetRelevantNodeAsync<TForEachStatement>().ConfigureAwait(false); if (foreachStatement == null || !IsValid(foreachStatement)) { return; } var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticFact = document.GetRequiredLanguageService<ISemanticFactsService>(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var foreachInfo = GetForeachInfo(semanticFact, model, foreachStatement, cancellationToken); if (foreachInfo == null || !ValidLocation(foreachInfo)) { return; } context.RegisterRefactoring( new ForEachToForCodeAction( Title, c => ConvertForeachToForAsync(document, foreachInfo, c)), foreachStatement.Span); } protected static SyntaxToken CreateUniqueName( ISemanticFactsService semanticFacts, SemanticModel model, SyntaxNode location, string baseName, CancellationToken cancellationToken) => semanticFacts.GenerateUniqueLocalName(model, location, containerOpt: null, baseName, cancellationToken); protected static SyntaxNode GetCollectionVariableName( SemanticModel model, SyntaxGenerator generator, ForEachInfo foreachInfo, SyntaxNode foreachCollectionExpression, CancellationToken cancellationToken) { if (foreachInfo.RequireCollectionStatement) { return generator.IdentifierName( CreateUniqueName(foreachInfo.SemanticFacts, model, foreachInfo.ForEachStatement, foreachInfo.CollectionNameSuggestion, cancellationToken)); } return foreachCollectionExpression.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation); } protected static void IntroduceCollectionStatement( ForEachInfo foreachInfo, SyntaxEditor editor, SyntaxNode type, SyntaxNode foreachCollectionExpression, SyntaxNode collectionVariable) { if (!foreachInfo.RequireCollectionStatement) { return; } // TODO: refactor introduce variable refactoring to real service and use that service here to introduce local variable var generator = editor.Generator; // attach rename annotation to control variable var collectionVariableToken = generator.Identifier(collectionVariable.ToString()).WithAdditionalAnnotations(RenameAnnotation.Create()); // this expression is from user code. don't simplify this. var expression = foreachCollectionExpression.WithoutAnnotations(SimplificationHelpers.DontSimplifyAnnotation); var collectionStatement = generator.LocalDeclarationStatement( type, collectionVariableToken, foreachInfo.RequireExplicitCastInterface ? generator.CastExpression(foreachInfo.ExplicitCastInterface, expression) : expression); // attach trivia to right place collectionStatement = collectionStatement.WithLeadingTrivia(foreachInfo.ForEachStatement.GetFirstToken().LeadingTrivia); editor.InsertBefore(foreachInfo.ForEachStatement, collectionStatement); } protected static TStatementSyntax AddItemVariableDeclaration( SyntaxGenerator generator, SyntaxNode type, SyntaxToken foreachVariable, ITypeSymbol castType, SyntaxNode collectionVariable, SyntaxToken indexVariable) { var memberAccess = generator.ElementAccessExpression( collectionVariable, generator.IdentifierName(indexVariable)); if (castType != null) { memberAccess = generator.CastExpression(castType, memberAccess); } var localDecl = generator.LocalDeclarationStatement( type, foreachVariable, memberAccess); return (TStatementSyntax)localDecl.WithAdditionalAnnotations(Formatter.Annotation); } private ForEachInfo? GetForeachInfo( ISemanticFactsService semanticFact, SemanticModel model, TForEachStatement foreachStatement, CancellationToken cancellationToken) { if (model.GetOperation(foreachStatement, cancellationToken) is not IForEachLoopOperation operation || operation.Locals.Length != 1) { return null; } var foreachVariable = operation.Locals[0]; if (foreachVariable == null) { return null; } // Perform language specific checks if the foreachStatement // is using unsupported features if (!IsSupported(foreachVariable, operation, foreachStatement)) { return null; } IsForEachVariableWrittenInside = CheckIfForEachVariableIsWrittenInside(model, foreachVariable, foreachStatement); var foreachCollection = RemoveImplicitConversion(operation.Collection); if (foreachCollection == null) { return null; } GetInterfaceInfo(model, foreachVariable, foreachCollection, out var explicitCastInterface, out var collectionNameSuggestion, out var countName); if (collectionNameSuggestion == null || countName == null) { return null; } var requireCollectionStatement = CheckRequireCollectionStatement(foreachCollection); return new ForEachInfo( semanticFact, collectionNameSuggestion, countName, explicitCastInterface, foreachVariable.Type, requireCollectionStatement, foreachStatement); } private static void GetInterfaceInfo( SemanticModel model, ILocalSymbol foreachVariable, IOperation foreachCollection, out ITypeSymbol? explicitCastInterface, out string? collectionNameSuggestion, out string? countName) { explicitCastInterface = null; collectionNameSuggestion = null; countName = null; // go through list of types and interfaces to find out right set; var foreachType = foreachVariable.Type; if (IsNullOrErrorType(foreachType)) { return; } var collectionType = foreachCollection.Type; if (IsNullOrErrorType(collectionType)) { return; } // go through explicit types first. // check array case if (collectionType is IArrayTypeSymbol array) { if (array.Rank != 1) { // array type supports IList and other interfaces, but implementation // only supports Rank == 1 case. other case, it will throw on runtime // even if there is no error on compile time. // we explicitly mark that we only support Rank == 1 case return; } if (!IsExchangable(array.ElementType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "array"; explicitCastInterface = null; countName = Length; return; } // check string case if (collectionType.SpecialType == SpecialType.System_String) { var charType = model.Compilation.GetSpecialType(SpecialType.System_Char); if (!IsExchangable(charType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "str"; explicitCastInterface = null; countName = Length; return; } // check ImmutableArray case if (collectionType.OriginalDefinition.Equals(model.Compilation.GetTypeByMetadataName(typeof(ImmutableArray<>).FullName!))) { var indexer = GetInterfaceMember(collectionType, get_Item); if (indexer != null) { if (!IsExchangable(indexer.ReturnType, foreachType, model.Compilation)) { return; } collectionNameSuggestion = "array"; explicitCastInterface = null; countName = Length; return; } } // go through all known interfaces we support next. var knownCollectionInterfaces = s_KnownInterfaceNames.Select( s => model.Compilation.GetTypeByMetadataName(s)).Where(t => !IsNullOrErrorType(t)); // for all interfaces, we suggest collection name as "list" collectionNameSuggestion = "list"; // check type itself is interface case if (collectionType.TypeKind == TypeKind.Interface && knownCollectionInterfaces.Contains(collectionType.OriginalDefinition)) { var indexer = GetInterfaceMember(collectionType, get_Item); if (indexer != null && IsExchangable(indexer.ReturnType, foreachType, model.Compilation)) { explicitCastInterface = null; countName = Count; return; } } // check regular cases (implicitly implemented) ITypeSymbol? explicitInterface = null; foreach (var current in collectionType.AllInterfaces) { if (!knownCollectionInterfaces.Contains(current.OriginalDefinition)) { continue; } // see how the type implements the interface var countSymbol = GetInterfaceMember(current, get_Count); var indexerSymbol = GetInterfaceMember(current, get_Item); if (countSymbol == null || indexerSymbol == null) { continue; } if (collectionType.FindImplementationForInterfaceMember(countSymbol) is not IMethodSymbol countImpl || collectionType.FindImplementationForInterfaceMember(indexerSymbol) is not IMethodSymbol indexerImpl) { continue; } if (!IsExchangable(indexerImpl.ReturnType, foreachType, model.Compilation)) { continue; } // implicitly implemented! if (countImpl.ExplicitInterfaceImplementations.IsEmpty && indexerImpl.ExplicitInterfaceImplementations.IsEmpty) { explicitCastInterface = null; countName = Count; return; } if (explicitInterface == null) { explicitInterface = current; } } // okay, we don't have implicitly implemented one, but we do have explicitly implemented one if (explicitInterface != null) { explicitCastInterface = explicitInterface; countName = Count; } } private static bool IsExchangable( ITypeSymbol type1, ITypeSymbol type2, Compilation compilation) { return compilation.HasImplicitConversion(type1, type2) || compilation.HasImplicitConversion(type2, type1); } private static bool IsNullOrErrorType([NotNullWhen(false)] ITypeSymbol? type) => type is null or IErrorTypeSymbol; private static IMethodSymbol? GetInterfaceMember(ITypeSymbol interfaceType, string memberName) { foreach (var current in interfaceType.GetAllInterfacesIncludingThis()) { var members = current.GetMembers(memberName); if (!members.IsEmpty && members[0] is IMethodSymbol method) { return method; } } return null; } private static bool CheckRequireCollectionStatement(IOperation operation) { // this lists type of references in collection part of foreach we will use // as it is in // var element = reference[indexer]; // // otherwise, we will introduce local variable for the expression first and then // do "foreach to for" refactoring // // foreach(var a in new int[] {....}) // to // var array = new int[] { ... } // foreach(var a in array) switch (operation.Kind) { case OperationKind.LocalReference: case OperationKind.FieldReference: case OperationKind.ParameterReference: case OperationKind.PropertyReference: case OperationKind.ArrayElementReference: return false; default: return true; } } private IOperation RemoveImplicitConversion(IOperation collection) { return (collection is IConversionOperation conversion && conversion.IsImplicit) ? RemoveImplicitConversion(conversion.Operand) : collection; } private bool CheckIfForEachVariableIsWrittenInside(SemanticModel semanticModel, ISymbol foreachVariable, TForEachStatement foreachStatement) { var (start, end) = GetForEachBody(foreachStatement); if (start == null || end == null) { // empty body. this can happen in VB return false; } var dataFlow = semanticModel.AnalyzeDataFlow(start, end); if (!dataFlow.Succeeded) { // if we can't get good analysis, assume it is written return true; } return dataFlow.WrittenInside.Contains(foreachVariable); } private async Task<Document> ConvertForeachToForAsync( Document document, ForEachInfo foreachInfo, CancellationToken cancellationToken) { var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var workspace = document.Project.Solution.Workspace; var editor = new SyntaxEditor(model.SyntaxTree.GetRoot(cancellationToken), workspace); ConvertToForStatement(model, foreachInfo, editor, cancellationToken); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } protected class ForEachInfo { public ForEachInfo( ISemanticFactsService semanticFacts, string collectionNameSuggestion, string countName, ITypeSymbol? explicitCastInterface, ITypeSymbol forEachElementType, bool requireCollectionStatement, TForEachStatement forEachStatement) { SemanticFacts = semanticFacts; RequireExplicitCastInterface = explicitCastInterface != null; CollectionNameSuggestion = collectionNameSuggestion; CountName = countName; ExplicitCastInterface = explicitCastInterface; ForEachElementType = forEachElementType; RequireCollectionStatement = requireCollectionStatement || (explicitCastInterface != null); ForEachStatement = forEachStatement; } public ISemanticFactsService SemanticFacts { get; } public bool RequireExplicitCastInterface { get; } public string CollectionNameSuggestion { get; } public string CountName { get; } public ITypeSymbol? ExplicitCastInterface { get; } public ITypeSymbol ForEachElementType { get; } public bool RequireCollectionStatement { get; } public TForEachStatement ForEachStatement { get; } } private class ForEachToForCodeAction : CodeAction.DocumentChangeAction { public ForEachToForCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingFatalErrorAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ErrorReporting; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingFatalErrorAccessor { public static bool ReportWithoutCrash(this Exception e) => FatalError.ReportAndCatch(e); public static bool ReportWithoutCrashUnlessCanceled(this Exception e) => FatalError.ReportAndCatchUnlessCanceled(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. #nullable disable using System; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingFatalErrorAccessor { public static bool ReportWithoutCrash(this Exception e) => FatalError.ReportAndCatch(e); public static bool ReportWithoutCrashUnlessCanceled(this Exception e) => FatalError.ReportAndCatchUnlessCanceled(e); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedInteractiveInitializerMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedInteractiveInitializerMethod : SynthesizedInstanceMethodSymbol { internal const string InitializerName = "<Initialize>"; private readonly SourceMemberContainerTypeSymbol _containingType; private readonly TypeSymbol _resultType; private readonly TypeSymbol _returnType; private ThreeState _lazyIsNullableAnalysisEnabled; internal SynthesizedInteractiveInitializerMethod(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) { Debug.Assert(containingType.IsScriptClass); _containingType = containingType; CalculateReturnType(containingType, diagnostics, out _resultType, out _returnType); } public override string Name { get { return InitializerName; } } internal override bool IsScriptInitializer { get { return true; } } public override int Arity { get { return this.TypeParameters.Length; } } public override Symbol AssociatedSymbol { get { return null; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Friend; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsAsync { get { return true; } } public override bool IsExtensionMethod { get { return false; } } public override bool IsExtern { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsStatic { get { return false; } } public override bool IsVararg { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override bool IsVirtual { get { return false; } } public override ImmutableArray<Location> Locations { get { return _containingType.Locations; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override bool ReturnsVoid { get { return _returnType.IsVoidType(); } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(!this.IsStatic); Debug.Assert(!this.IsGenericMethod); return Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return true; } } internal override bool HasDeclarativeSecurity { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override MethodImplAttributes ImplementationAttributes { get { return default(MethodImplAttributes); } } internal override bool RequiresSecurityObject { get { return false; } } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } public override DllImportData GetDllImportData() { return null; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return _containingType.CalculateSyntaxOffsetInSynthesizedConstructor(localPosition, localTree, isStatic: false); } internal TypeSymbol ResultType { get { return _resultType; } } internal override bool IsNullableAnalysisEnabled() { if (_lazyIsNullableAnalysisEnabled == ThreeState.Unknown) { // Return true if nullable is not disabled in compilation options or if enabled // in any syntax tree. This could be refined to ignore top-level methods and // type declarations but this simple approach matches C#8 behavior. var compilation = DeclaringCompilation; bool value = (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) || compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new TextSpan(0, tree.Length)) == true); _lazyIsNullableAnalysisEnabled = value.ToThreeState(); } return _lazyIsNullableAnalysisEnabled == ThreeState.True; } private static void CalculateReturnType( SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics, out TypeSymbol resultType, out TypeSymbol returnType) { CSharpCompilation compilation = containingType.DeclaringCompilation; var submissionReturnTypeOpt = compilation.ScriptCompilationInfo?.ReturnTypeOpt; var taskT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); diagnostics.ReportUseSite(taskT, NoLocation.Singleton); // If no explicit return type is set on ScriptCompilationInfo, default to // System.Object from the target corlib. This allows cross compiling scripts // to run on a target corlib that may differ from the host compiler's corlib. // cf. https://github.com/dotnet/roslyn/issues/8506 resultType = (object)submissionReturnTypeOpt == null ? compilation.GetSpecialType(SpecialType.System_Object) : compilation.GetTypeByReflectionType(submissionReturnTypeOpt, diagnostics); returnType = taskT.Construct(resultType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedInteractiveInitializerMethod : SynthesizedInstanceMethodSymbol { internal const string InitializerName = "<Initialize>"; private readonly SourceMemberContainerTypeSymbol _containingType; private readonly TypeSymbol _resultType; private readonly TypeSymbol _returnType; private ThreeState _lazyIsNullableAnalysisEnabled; internal SynthesizedInteractiveInitializerMethod(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) { Debug.Assert(containingType.IsScriptClass); _containingType = containingType; CalculateReturnType(containingType, diagnostics, out _resultType, out _returnType); } public override string Name { get { return InitializerName; } } internal override bool IsScriptInitializer { get { return true; } } public override int Arity { get { return this.TypeParameters.Length; } } public override Symbol AssociatedSymbol { get { return null; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Friend; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsAsync { get { return true; } } public override bool IsExtensionMethod { get { return false; } } public override bool IsExtern { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsStatic { get { return false; } } public override bool IsVararg { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override bool IsVirtual { get { return false; } } public override ImmutableArray<Location> Locations { get { return _containingType.Locations; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override bool ReturnsVoid { get { return _returnType.IsVoidType(); } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(!this.IsStatic); Debug.Assert(!this.IsGenericMethod); return Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return true; } } internal override bool HasDeclarativeSecurity { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override MethodImplAttributes ImplementationAttributes { get { return default(MethodImplAttributes); } } internal override bool RequiresSecurityObject { get { return false; } } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } public override DllImportData GetDllImportData() { return null; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return _containingType.CalculateSyntaxOffsetInSynthesizedConstructor(localPosition, localTree, isStatic: false); } internal TypeSymbol ResultType { get { return _resultType; } } internal override bool IsNullableAnalysisEnabled() { if (_lazyIsNullableAnalysisEnabled == ThreeState.Unknown) { // Return true if nullable is not disabled in compilation options or if enabled // in any syntax tree. This could be refined to ignore top-level methods and // type declarations but this simple approach matches C#8 behavior. var compilation = DeclaringCompilation; bool value = (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) || compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new TextSpan(0, tree.Length)) == true); _lazyIsNullableAnalysisEnabled = value.ToThreeState(); } return _lazyIsNullableAnalysisEnabled == ThreeState.True; } private static void CalculateReturnType( SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics, out TypeSymbol resultType, out TypeSymbol returnType) { CSharpCompilation compilation = containingType.DeclaringCompilation; var submissionReturnTypeOpt = compilation.ScriptCompilationInfo?.ReturnTypeOpt; var taskT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); diagnostics.ReportUseSite(taskT, NoLocation.Singleton); // If no explicit return type is set on ScriptCompilationInfo, default to // System.Object from the target corlib. This allows cross compiling scripts // to run on a target corlib that may differ from the host compiler's corlib. // cf. https://github.com/dotnet/roslyn/issues/8506 resultType = (object)submissionReturnTypeOpt == null ? compilation.GetSpecialType(SpecialType.System_Object) : compilation.GetTypeByReflectionType(submissionReturnTypeOpt, diagnostics); returnType = taskT.Construct(resultType); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/RQName/RQNameInternal.cs
// Licensed to the .NET Foundation under one or more 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.Features.RQName { /// <summary> /// Helpers related to <see cref="RQName"/>s. /// </summary> internal static class RQNameInternal { /// <summary> /// Returns an RQName for the given symbol, or <see langword="null"/> if the symbol cannot be represented by an RQName. /// </summary> /// <param name="symbol">The symbol to build an RQName for.</param> public static string? From(ISymbol symbol) { var node = RQNodeBuilder.Build(symbol); if (node == null) { return null; } return ParenthesesTreeWriter.ToParenthesesFormat(node.ToSimpleTree()); } } }
// Licensed to the .NET Foundation under one or more 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.Features.RQName { /// <summary> /// Helpers related to <see cref="RQName"/>s. /// </summary> internal static class RQNameInternal { /// <summary> /// Returns an RQName for the given symbol, or <see langword="null"/> if the symbol cannot be represented by an RQName. /// </summary> /// <param name="symbol">The symbol to build an RQName for.</param> public static string? From(ISymbol symbol) { var node = RQNodeBuilder.Build(symbol); if (node == null) { return null; } return ParenthesesTreeWriter.ToParenthesesFormat(node.ToSimpleTree()); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Dependencies/Collections/Internal/ICollectionDebugView`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Collections.Internal { internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; public ICollectionDebugView(ICollection<T> collection) { _collection = collection ?? throw new ArgumentNullException(nameof(collection)); } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Collections.Internal { internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; public ICollectionDebugView(ICollection<T> collection) { _collection = collection ?? throw new ArgumentNullException(nameof(collection)); } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Remote/RemoteServiceConnection.cs
// Licensed to the .NET Foundation under one or more 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.IO.Pipelines; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstracts a connection to a legacy remote service. /// </summary> internal abstract class RemoteServiceConnection : IDisposable { public abstract void Dispose(); public abstract Task RunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken); public abstract Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>>? dataReader, CancellationToken cancellationToken); public Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => RunRemoteAsync<T>(targetName, solution, arguments, dataReader: null, cancellationToken); } /// <summary> /// Abstracts a connection to a service implementing type <typeparamref name="TService"/>. /// </summary> /// <typeparam name="TService">Remote interface type of the service.</typeparam> internal abstract class RemoteServiceConnection<TService> : IDisposable where TService : class { public abstract void Dispose(); // no solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); // no solution, callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, no callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // streaming public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstracts a connection to a legacy remote service. /// </summary> internal abstract class RemoteServiceConnection : IDisposable { public abstract void Dispose(); public abstract Task RunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken); public abstract Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>>? dataReader, CancellationToken cancellationToken); public Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => RunRemoteAsync<T>(targetName, solution, arguments, dataReader: null, cancellationToken); } /// <summary> /// Abstracts a connection to a service implementing type <typeparamref name="TService"/>. /// </summary> /// <typeparam name="TService">Remote interface type of the service.</typeparam> internal abstract class RemoteServiceConnection<TService> : IDisposable where TService : class { public abstract void Dispose(); // no solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); // no solution, callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, no callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // streaming public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/TestUtilities/Threading/StaTaskScheduler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Test.Utilities; namespace Roslyn.Test.Utilities { public sealed class StaTaskScheduler : IDisposable { /// <summary>Gets a <see cref="StaTaskScheduler"/> for the current <see cref="AppDomain"/>.</summary> /// <remarks>We use a count of 1, because the editor ends up re-using <see cref="DispatcherObject"/> /// instances between tests, so we need to always use the same thread for our Sta tests.</remarks> public static StaTaskScheduler DefaultSta { get; } = new StaTaskScheduler(); /// <summary>The STA threads used by the scheduler.</summary> public Thread StaThread { get; } public bool IsRunningInScheduler => StaThread.ManagedThreadId == Environment.CurrentManagedThreadId; static StaTaskScheduler() { // Overwrite xunit's app domain handling to not call AppDomain.Unload var getDefaultDomain = typeof(AppDomain).GetMethod("GetDefaultDomain", BindingFlags.NonPublic | BindingFlags.Static); var defaultDomain = (AppDomain)getDefaultDomain.Invoke(null, null); var hook = (XunitDisposeHook)defaultDomain.CreateInstanceFromAndUnwrap(typeof(XunitDisposeHook).Assembly.CodeBase, typeof(XunitDisposeHook).FullName, ignoreCase: false, BindingFlags.CreateInstance, binder: null, args: null, culture: null, activationAttributes: null); hook.Execute(); // We've created an STA thread, which has some extra requirements for COM Runtime // Callable Wrappers (RCWs). If any COM object is created on the STA thread, calls to that // object must be made from that thread; when the RCW is no longer being used by any // managed code, the RCW is put into the finalizer queue, but to actually finalize it // it has to marshal to the STA thread to do the work. This means that in order to safely // clean up any RCWs, we need to ensure that the thread is pumping past the point of // all RCWs being finalized // // This constraint is particularly problematic if our tests are running in an AppDomain: // when the AppDomain is unloaded, any threads (including our STA thread) are going to be // aborted. Once the thread and AppDomain is being torn down, the CLR is going to try cleaning up // any RCWs associated them, because if the thread is gone for good there's no way // it could ever clean anything further up. The code there waits for the finalizer queue // -- but the finalizer queue might be already trying to clean up an RCW, which is marshaling // to the STA thread. This could then deadlock. // // The suggested workaround from the CLR team is to do an explicit GC.Collect and // WaitForPendingFinalizers before we let the AppDomain shut down. The belief is subscribing // to DomainUnload is a reasonable place to do it. AppDomain.CurrentDomain.DomainUnload += (sender, e) => { GC.Collect(); GC.WaitForPendingFinalizers(); }; } /// <summary>Initializes a new instance of the <see cref="StaTaskScheduler"/> class.</summary> public StaTaskScheduler() { using (var threadStartedEvent = new ManualResetEventSlim(initialState: false)) { DispatcherSynchronizationContext synchronizationContext = null; StaThread = new Thread(() => { var oldContext = SynchronizationContext.Current; try { // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard // or mouse input from the user. So use background priority which is a single level below user input. synchronizationContext = new DispatcherSynchronizationContext(); // xUnit creates its own synchronization context and wraps any existing context so that messages are // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test. SynchronizationContext.SetSynchronizationContext(synchronizationContext); threadStartedEvent.Set(); Dispatcher.Run(); } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } }); StaThread.Name = $"{nameof(StaTaskScheduler)} thread"; StaThread.IsBackground = true; StaThread.SetApartmentState(ApartmentState.STA); StaThread.Start(); threadStartedEvent.Wait(); DispatcherSynchronizationContext = synchronizationContext; } // Work around the WeakEventTable Shutdown race conditions AppContext.SetSwitch("Switch.MS.Internal.DoNotInvokeInWeakEventTableShutdownListener", isEnabled: true); } public DispatcherSynchronizationContext DispatcherSynchronizationContext { get; } /// <summary> /// Cleans up the scheduler by indicating that no more tasks will be queued. /// This method blocks until all threads successfully shutdown. /// </summary> public void Dispose() { if (StaThread.IsAlive) { DispatcherSynchronizationContext.Post(_ => Dispatcher.ExitAllFrames(), null); StaThread.Join(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Test.Utilities; namespace Roslyn.Test.Utilities { public sealed class StaTaskScheduler : IDisposable { /// <summary>Gets a <see cref="StaTaskScheduler"/> for the current <see cref="AppDomain"/>.</summary> /// <remarks>We use a count of 1, because the editor ends up re-using <see cref="DispatcherObject"/> /// instances between tests, so we need to always use the same thread for our Sta tests.</remarks> public static StaTaskScheduler DefaultSta { get; } = new StaTaskScheduler(); /// <summary>The STA threads used by the scheduler.</summary> public Thread StaThread { get; } public bool IsRunningInScheduler => StaThread.ManagedThreadId == Environment.CurrentManagedThreadId; static StaTaskScheduler() { // Overwrite xunit's app domain handling to not call AppDomain.Unload var getDefaultDomain = typeof(AppDomain).GetMethod("GetDefaultDomain", BindingFlags.NonPublic | BindingFlags.Static); var defaultDomain = (AppDomain)getDefaultDomain.Invoke(null, null); var hook = (XunitDisposeHook)defaultDomain.CreateInstanceFromAndUnwrap(typeof(XunitDisposeHook).Assembly.CodeBase, typeof(XunitDisposeHook).FullName, ignoreCase: false, BindingFlags.CreateInstance, binder: null, args: null, culture: null, activationAttributes: null); hook.Execute(); // We've created an STA thread, which has some extra requirements for COM Runtime // Callable Wrappers (RCWs). If any COM object is created on the STA thread, calls to that // object must be made from that thread; when the RCW is no longer being used by any // managed code, the RCW is put into the finalizer queue, but to actually finalize it // it has to marshal to the STA thread to do the work. This means that in order to safely // clean up any RCWs, we need to ensure that the thread is pumping past the point of // all RCWs being finalized // // This constraint is particularly problematic if our tests are running in an AppDomain: // when the AppDomain is unloaded, any threads (including our STA thread) are going to be // aborted. Once the thread and AppDomain is being torn down, the CLR is going to try cleaning up // any RCWs associated them, because if the thread is gone for good there's no way // it could ever clean anything further up. The code there waits for the finalizer queue // -- but the finalizer queue might be already trying to clean up an RCW, which is marshaling // to the STA thread. This could then deadlock. // // The suggested workaround from the CLR team is to do an explicit GC.Collect and // WaitForPendingFinalizers before we let the AppDomain shut down. The belief is subscribing // to DomainUnload is a reasonable place to do it. AppDomain.CurrentDomain.DomainUnload += (sender, e) => { GC.Collect(); GC.WaitForPendingFinalizers(); }; } /// <summary>Initializes a new instance of the <see cref="StaTaskScheduler"/> class.</summary> public StaTaskScheduler() { using (var threadStartedEvent = new ManualResetEventSlim(initialState: false)) { DispatcherSynchronizationContext synchronizationContext = null; StaThread = new Thread(() => { var oldContext = SynchronizationContext.Current; try { // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard // or mouse input from the user. So use background priority which is a single level below user input. synchronizationContext = new DispatcherSynchronizationContext(); // xUnit creates its own synchronization context and wraps any existing context so that messages are // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test. SynchronizationContext.SetSynchronizationContext(synchronizationContext); threadStartedEvent.Set(); Dispatcher.Run(); } finally { SynchronizationContext.SetSynchronizationContext(oldContext); } }); StaThread.Name = $"{nameof(StaTaskScheduler)} thread"; StaThread.IsBackground = true; StaThread.SetApartmentState(ApartmentState.STA); StaThread.Start(); threadStartedEvent.Wait(); DispatcherSynchronizationContext = synchronizationContext; } // Work around the WeakEventTable Shutdown race conditions AppContext.SetSwitch("Switch.MS.Internal.DoNotInvokeInWeakEventTableShutdownListener", isEnabled: true); } public DispatcherSynchronizationContext DispatcherSynchronizationContext { get; } /// <summary> /// Cleans up the scheduler by indicating that no more tasks will be queued. /// This method blocks until all threads successfully shutdown. /// </summary> public void Dispose() { if (StaThread.IsAlive) { DispatcherSynchronizationContext.Post(_ => Dispatcher.ExitAllFrames(), null); StaThread.Join(); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Syntax/Parsing/CrefParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Test.Utilities; using System; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CrefParsingTests : ParsingTests { public CrefParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <see cref=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlCrefAttributeSyntax>().Single(); return attr.Cref; } #region Name members #region Unqualified [Fact] public void UnqualifiedNameMember1() { UsingNode("A"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnqualifiedNameMember2() { UsingNode("A{B}"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } } [Fact] public void UnqualifiedNameMember3() { UsingNode("A()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void UnqualifiedNameMember4() { UsingNode("A{B}()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedNameMember1() { UsingNode("T.A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void QualifiedNameMember2() { UsingNode("T.A{B}"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } } } [Fact] public void QualifiedNameMember3() { UsingNode("T.A()"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } [Fact] public void QualifiedNameMember4() { UsingNode("T.A{B}()"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #endregion Name Members #region Indexer members #region Unqualified [Fact] public void UnqualifiedIndexerMember1() { UsingNode("this"); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); } } [Fact] public void UnqualifiedIndexerMember2() { UsingNode("this[A]"); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.CrefBracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedIndexerMember1() { UsingNode("T.this"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); } } } [Fact] public void QualifiedIndexerMember2() { UsingNode("T.this[A]"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.CrefBracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } } } #endregion Qualified #endregion Indexer Members #region Operator members #region Unqualified [Fact] public void UnqualifiedOperatorMember1() { UsingNode("operator +"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); } } [Fact] public void UnqualifiedOperatorMember2() { UsingNode("operator +(A)"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedOperatorMember1() { UsingNode("T.operator +"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); } } } [Fact] public void QualifiedOperatorMember2() { UsingNode("T.operator +(A)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #region Ambiguities [WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")] [Fact] public void GreaterThanGreaterThan() { UsingNode("operator }}(A{A{T}})"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.GreaterThanGreaterThanToken); // >> N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); // just > } } N(SyntaxKind.GreaterThanToken); // just > } } } N(SyntaxKind.CloseParenToken); } } EOF(); } #endregion Ambiguities #endregion Operator Members #region Conversion Operator members #region Unqualified [Fact] public void UnqualifiedConversionOperatorMember1() { UsingNode("implicit operator A"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnqualifiedConversionOperatorMember2() { UsingNode("explicit operator A(B)"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedConversionOperatorMember1() { UsingNode("T.implicit operator A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void QualifiedConversionOperatorMember2() { UsingNode("T.explicit operator A(B)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #endregion Conversion Operator Members #region Parameters [Fact] public void ParameterCount() { UsingNode("A()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } UsingNode("A(B)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } UsingNode("A(B, C)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterRefKind() { UsingNode("A(ref B, out C)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterNullableType() { UsingNode("A(B?)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterPointerType() { UsingNode("A(B*, C**)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CloseParenToken); } } } [WorkItem(531157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531157")] [Fact] public void ParameterVoidPointerType() { UsingNode("IntPtr.op_Explicit(void*)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ParameterArrayType() { UsingNode("A(B[], C[,][,,])"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterComplex() { UsingNode("A(ref int?*[], out B::C{D}.E?[,][])"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); } } } [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void NestedArrayTypes() { UsingNode("F(A{int[], B?, C?*[,]})"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.CloseParenToken); } } EOF(); } #endregion Parameters #region Conversion operator return types [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void PrimitiveArrayReturnType() { UsingNode("explicit operator int[]"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void NamedTypeArrayReturnType() { UsingNode("explicit operator C[]"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } #endregion Conversion operator return types #region Qualified [Fact] public void Qualified1() { // NOTE: since int.A won't fit into a TypeSyntax, it is represented as // a qualified cref member instead. UsingNode("int.A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified2() { UsingNode("A.B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified3() { UsingNode("A{T}.B{U, V}.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified4() { UsingNode("Alias::B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified5() { UsingNode("global::B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } #endregion Qualified #region Aliased or Predefined [Fact] public void AliasedOrPredefined1() { UsingNode("string"); N(SyntaxKind.TypeCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } [Fact] public void AliasedOrPredefined2() { UsingNode("Alias::B"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void AliasedOrPredefined3() { UsingNode("global::B"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void AliasedOrPredefined4() { UsingNode("global::global"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } #endregion Aliased or Predefined #region Identifiers [Fact] public void EscapedKeyword() { UsingNode("@string"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void EscapedUnicode() { UsingNode(@"\u0061"); // a N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnescapedUnicode() { UsingNode("\u00CB"); // E with umlaut N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void InvalidIdentifier() { UsingNode("2"); M(SyntaxKind.NameMemberCref); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } #endregion Identifiers #region Non-simple-type constructors [Fact] public void PredefinedTypeConstructor() { UsingNode("string()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void AliasQualifiedTypeConstructor() { UsingNode("Alias::B()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void AliasQualifiedGenericTypeConstructor() { UsingNode("Alias::B{T}()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } #endregion Non-simple-type constructors } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Test.Utilities; using System; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CrefParsingTests : ParsingTests { public CrefParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <see cref=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlCrefAttributeSyntax>().Single(); return attr.Cref; } #region Name members #region Unqualified [Fact] public void UnqualifiedNameMember1() { UsingNode("A"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnqualifiedNameMember2() { UsingNode("A{B}"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } } [Fact] public void UnqualifiedNameMember3() { UsingNode("A()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void UnqualifiedNameMember4() { UsingNode("A{B}()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedNameMember1() { UsingNode("T.A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void QualifiedNameMember2() { UsingNode("T.A{B}"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } } } [Fact] public void QualifiedNameMember3() { UsingNode("T.A()"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } [Fact] public void QualifiedNameMember4() { UsingNode("T.A{B}()"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #endregion Name Members #region Indexer members #region Unqualified [Fact] public void UnqualifiedIndexerMember1() { UsingNode("this"); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); } } [Fact] public void UnqualifiedIndexerMember2() { UsingNode("this[A]"); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.CrefBracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedIndexerMember1() { UsingNode("T.this"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); } } } [Fact] public void QualifiedIndexerMember2() { UsingNode("T.this[A]"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IndexerMemberCref); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.CrefBracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } } } #endregion Qualified #endregion Indexer Members #region Operator members #region Unqualified [Fact] public void UnqualifiedOperatorMember1() { UsingNode("operator +"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); } } [Fact] public void UnqualifiedOperatorMember2() { UsingNode("operator +(A)"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedOperatorMember1() { UsingNode("T.operator +"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); } } } [Fact] public void QualifiedOperatorMember2() { UsingNode("T.operator +(A)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #region Ambiguities [WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")] [Fact] public void GreaterThanGreaterThan() { UsingNode("operator }}(A{A{T}})"); N(SyntaxKind.OperatorMemberCref); { N(SyntaxKind.OperatorKeyword); N(SyntaxKind.GreaterThanGreaterThanToken); // >> N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); // just > } } N(SyntaxKind.GreaterThanToken); // just > } } } N(SyntaxKind.CloseParenToken); } } EOF(); } #endregion Ambiguities #endregion Operator Members #region Conversion Operator members #region Unqualified [Fact] public void UnqualifiedConversionOperatorMember1() { UsingNode("implicit operator A"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnqualifiedConversionOperatorMember2() { UsingNode("explicit operator A(B)"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } #endregion Unqualified #region Qualified [Fact] public void QualifiedConversionOperatorMember1() { UsingNode("T.implicit operator A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void QualifiedConversionOperatorMember2() { UsingNode("T.explicit operator A(B)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } } #endregion Qualified #endregion Conversion Operator Members #region Parameters [Fact] public void ParameterCount() { UsingNode("A()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } UsingNode("A(B)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } UsingNode("A(B, C)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterRefKind() { UsingNode("A(ref B, out C)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterNullableType() { UsingNode("A(B?)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterPointerType() { UsingNode("A(B*, C**)"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CloseParenToken); } } } [WorkItem(531157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531157")] [Fact] public void ParameterVoidPointerType() { UsingNode("IntPtr.op_Explicit(void*)"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.AsteriskToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ParameterArrayType() { UsingNode("A(B[], C[,][,,])"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); } } } [Fact] public void ParameterComplex() { UsingNode("A(ref int?*[], out B::C{D}.E?[,][])"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); } } } [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void NestedArrayTypes() { UsingNode("F(A{int[], B?, C?*[,]})"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CrefParameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.CloseParenToken); } } EOF(); } #endregion Parameters #region Conversion operator return types [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void PrimitiveArrayReturnType() { UsingNode("explicit operator int[]"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [WorkItem(531154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531154")] [Fact] public void NamedTypeArrayReturnType() { UsingNode("explicit operator C[]"); N(SyntaxKind.ConversionOperatorMemberCref); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } #endregion Conversion operator return types #region Qualified [Fact] public void Qualified1() { // NOTE: since int.A won't fit into a TypeSyntax, it is represented as // a qualified cref member instead. UsingNode("int.A"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified2() { UsingNode("A.B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified3() { UsingNode("A{T}.B{U, V}.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified4() { UsingNode("Alias::B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void Qualified5() { UsingNode("global::B.C"); N(SyntaxKind.QualifiedCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } #endregion Qualified #region Aliased or Predefined [Fact] public void AliasedOrPredefined1() { UsingNode("string"); N(SyntaxKind.TypeCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } [Fact] public void AliasedOrPredefined2() { UsingNode("Alias::B"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void AliasedOrPredefined3() { UsingNode("global::B"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } [Fact] public void AliasedOrPredefined4() { UsingNode("global::global"); N(SyntaxKind.TypeCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } #endregion Aliased or Predefined #region Identifiers [Fact] public void EscapedKeyword() { UsingNode("@string"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void EscapedUnicode() { UsingNode(@"\u0061"); // a N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void UnescapedUnicode() { UsingNode("\u00CB"); // E with umlaut N(SyntaxKind.NameMemberCref); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } [Fact] public void InvalidIdentifier() { UsingNode("2"); M(SyntaxKind.NameMemberCref); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } #endregion Identifiers #region Non-simple-type constructors [Fact] public void PredefinedTypeConstructor() { UsingNode("string()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void AliasQualifiedTypeConstructor() { UsingNode("Alias::B()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } [Fact] public void AliasQualifiedGenericTypeConstructor() { UsingNode("Alias::B{T}()"); N(SyntaxKind.NameMemberCref); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.CrefParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } #endregion Non-simple-type constructors } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Core/CompilerTraitAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { [TraitDiscoverer("Microsoft.CodeAnalysis.Test.Utilities.CompilerTraitDiscoverer", assemblyName: "Roslyn.Test.Utilities")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class CompilerTraitAttribute : Attribute, ITraitAttribute { public CompilerFeature[] Features { get; } public CompilerTraitAttribute(params CompilerFeature[] features) { Features = features; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { [TraitDiscoverer("Microsoft.CodeAnalysis.Test.Utilities.CompilerTraitDiscoverer", assemblyName: "Roslyn.Test.Utilities")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class CompilerTraitAttribute : Attribute, ITraitAttribute { public CompilerFeature[] Features { get; } public CompilerTraitAttribute(params CompilerFeature[] features) { Features = features; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UseCollectionInitializer { internal abstract partial class AbstractUseCollectionInitializerDiagnosticAnalyzer< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TInvocationExpressionSyntax : TExpressionSyntax where TExpressionStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected AbstractUseCollectionInitializerDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCollectionInitializerDiagnosticId, EnforceOnBuildValues.UseCollectionInitializer, CodeStyleOptions2.PreferCollectionInitializer, new LocalizableResourceString(nameof(AnalyzersResources.Simplify_collection_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Collection_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterCompilationStartAction(OnCompilationStart); private void OnCompilationStart(CompilationStartAnalysisContext context) { if (!AreCollectionInitializersSupported(context.Compilation)) { return; } var ienumerableType = context.Compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName!); if (ienumerableType != null) { var syntaxKinds = GetSyntaxFacts().SyntaxKinds; context.RegisterSyntaxNodeAction( nodeContext => AnalyzeNode(nodeContext, ienumerableType), syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression)); } } protected abstract bool AreCollectionInitializersSupported(Compilation compilation); private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ienumerableType) { var semanticModel = context.SemanticModel; var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node; var language = objectCreationExpression.Language; var cancellationToken = context.CancellationToken; var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language); if (!option.Value) { // not point in analyzing if the option is off. return; } // Object creation can only be converted to collection initializer if it // implements the IEnumerable type. var objectType = context.SemanticModel.GetTypeInfo(objectCreationExpression, cancellationToken); if (objectType.Type == null || !objectType.Type.AllInterfaces.Contains(ienumerableType)) { return; } var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, GetSyntaxFacts(), objectCreationExpression, cancellationToken); if (matches == null || matches.Value.Length == 0) { return; } var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>(); if (containingStatement == null) { return; } var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value); var syntaxFacts = GetSyntaxFacts(); if (syntaxFacts.ContainsInterleavedDirective(nodes, cancellationToken)) { return; } var locations = ImmutableArray.Create(objectCreationExpression.GetLocation()); var severity = option.Notification.Severity; context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, objectCreationExpression.GetLocation(), severity, additionalLocations: locations, properties: null)); FadeOutCode(context, matches.Value, locations); } private void FadeOutCode( SyntaxNodeAnalysisContext context, ImmutableArray<TExpressionStatementSyntax> matches, ImmutableArray<Location> locations) { var syntaxTree = context.Node.SyntaxTree; var fadeOutCode = context.GetOption( CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language); if (!fadeOutCode) { return; } var syntaxFacts = GetSyntaxFacts(); foreach (var match in matches) { var expression = syntaxFacts.GetExpressionOfExpressionStatement(match); if (syntaxFacts.IsInvocationExpression(expression)) { var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(expression); var additionalUnnecessaryLocations = ImmutableArray.Create( syntaxTree.GetLocation(TextSpan.FromBounds(match.SpanStart, arguments[0].SpanStart)), syntaxTree.GetLocation(TextSpan.FromBounds(arguments.Last().FullSpan.End, match.Span.End))); // Report the diagnostic at the first unnecessary location. This is the location where the code fix // will be offered. var location1 = additionalUnnecessaryLocations[0]; context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags( Descriptor, location1, ReportDiagnostic.Default, additionalLocations: locations, additionalUnnecessaryLocations: additionalUnnecessaryLocations)); } } } protected abstract ISyntaxFacts GetSyntaxFacts(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UseCollectionInitializer { internal abstract partial class AbstractUseCollectionInitializerDiagnosticAnalyzer< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TInvocationExpressionSyntax : TExpressionSyntax where TExpressionStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected AbstractUseCollectionInitializerDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCollectionInitializerDiagnosticId, EnforceOnBuildValues.UseCollectionInitializer, CodeStyleOptions2.PreferCollectionInitializer, new LocalizableResourceString(nameof(AnalyzersResources.Simplify_collection_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Collection_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterCompilationStartAction(OnCompilationStart); private void OnCompilationStart(CompilationStartAnalysisContext context) { if (!AreCollectionInitializersSupported(context.Compilation)) { return; } var ienumerableType = context.Compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName!); if (ienumerableType != null) { var syntaxKinds = GetSyntaxFacts().SyntaxKinds; context.RegisterSyntaxNodeAction( nodeContext => AnalyzeNode(nodeContext, ienumerableType), syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression)); } } protected abstract bool AreCollectionInitializersSupported(Compilation compilation); private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ienumerableType) { var semanticModel = context.SemanticModel; var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node; var language = objectCreationExpression.Language; var cancellationToken = context.CancellationToken; var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language); if (!option.Value) { // not point in analyzing if the option is off. return; } // Object creation can only be converted to collection initializer if it // implements the IEnumerable type. var objectType = context.SemanticModel.GetTypeInfo(objectCreationExpression, cancellationToken); if (objectType.Type == null || !objectType.Type.AllInterfaces.Contains(ienumerableType)) { return; } var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, GetSyntaxFacts(), objectCreationExpression, cancellationToken); if (matches == null || matches.Value.Length == 0) { return; } var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>(); if (containingStatement == null) { return; } var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value); var syntaxFacts = GetSyntaxFacts(); if (syntaxFacts.ContainsInterleavedDirective(nodes, cancellationToken)) { return; } var locations = ImmutableArray.Create(objectCreationExpression.GetLocation()); var severity = option.Notification.Severity; context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, objectCreationExpression.GetLocation(), severity, additionalLocations: locations, properties: null)); FadeOutCode(context, matches.Value, locations); } private void FadeOutCode( SyntaxNodeAnalysisContext context, ImmutableArray<TExpressionStatementSyntax> matches, ImmutableArray<Location> locations) { var syntaxTree = context.Node.SyntaxTree; var fadeOutCode = context.GetOption( CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language); if (!fadeOutCode) { return; } var syntaxFacts = GetSyntaxFacts(); foreach (var match in matches) { var expression = syntaxFacts.GetExpressionOfExpressionStatement(match); if (syntaxFacts.IsInvocationExpression(expression)) { var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(expression); var additionalUnnecessaryLocations = ImmutableArray.Create( syntaxTree.GetLocation(TextSpan.FromBounds(match.SpanStart, arguments[0].SpanStart)), syntaxTree.GetLocation(TextSpan.FromBounds(arguments.Last().FullSpan.End, match.Span.End))); // Report the diagnostic at the first unnecessary location. This is the location where the code fix // will be offered. var location1 = additionalUnnecessaryLocations[0]; context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags( Descriptor, location1, ReportDiagnostic.Default, additionalLocations: locations, additionalUnnecessaryLocations: additionalUnnecessaryLocations)); } } } protected abstract ISyntaxFacts GetSyntaxFacts(); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/InlineRename/RenameLogMessage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal static class RenameLogMessage { private const string RenameInComments = nameof(RenameInComments); private const string RenameInStrings = nameof(RenameInStrings); private const string RenameOverloads = nameof(RenameOverloads); private const string Committed = nameof(Committed); private const string Canceled = nameof(Canceled); private const string ConflictResolutionFinishedComputing = nameof(ConflictResolutionFinishedComputing); private const string PreviewChanges = nameof(PreviewChanges); private const string RenamedIdentifiersWithoutConflicts = nameof(RenamedIdentifiersWithoutConflicts); private const string ResolvableReferenceConflicts = nameof(ResolvableReferenceConflicts); private const string ResolvableNonReferenceConflicts = nameof(ResolvableNonReferenceConflicts); private const string UnresolvableConflicts = nameof(UnresolvableConflicts); public static KeyValueLogMessage Create( OptionSet optionSet, UserActionOutcome outcome, bool conflictResolutionFinishedComputing, bool previewChanges, IList<InlineRenameReplacementKind> replacementKinds) { return KeyValueLogMessage.Create(LogType.UserAction, m => { m[RenameInComments] = optionSet.GetOption(RenameOptions.RenameInComments); m[RenameInStrings] = optionSet.GetOption(RenameOptions.RenameInStrings); m[RenameOverloads] = optionSet.GetOption(RenameOptions.RenameOverloads); m[Committed] = (outcome & UserActionOutcome.Committed) == UserActionOutcome.Committed; m[Canceled] = (outcome & UserActionOutcome.Canceled) == UserActionOutcome.Canceled; m[ConflictResolutionFinishedComputing] = conflictResolutionFinishedComputing; m[PreviewChanges] = previewChanges; m[RenamedIdentifiersWithoutConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.NoConflict); m[ResolvableReferenceConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.ResolvedReferenceConflict); m[ResolvableNonReferenceConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.ResolvedNonReferenceConflict); m[UnresolvableConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.UnresolvedConflict); }); } [Flags] public enum UserActionOutcome { Committed = 0x1, Canceled = 0x2, } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal static class RenameLogMessage { private const string RenameInComments = nameof(RenameInComments); private const string RenameInStrings = nameof(RenameInStrings); private const string RenameOverloads = nameof(RenameOverloads); private const string Committed = nameof(Committed); private const string Canceled = nameof(Canceled); private const string ConflictResolutionFinishedComputing = nameof(ConflictResolutionFinishedComputing); private const string PreviewChanges = nameof(PreviewChanges); private const string RenamedIdentifiersWithoutConflicts = nameof(RenamedIdentifiersWithoutConflicts); private const string ResolvableReferenceConflicts = nameof(ResolvableReferenceConflicts); private const string ResolvableNonReferenceConflicts = nameof(ResolvableNonReferenceConflicts); private const string UnresolvableConflicts = nameof(UnresolvableConflicts); public static KeyValueLogMessage Create( OptionSet optionSet, UserActionOutcome outcome, bool conflictResolutionFinishedComputing, bool previewChanges, IList<InlineRenameReplacementKind> replacementKinds) { return KeyValueLogMessage.Create(LogType.UserAction, m => { m[RenameInComments] = optionSet.GetOption(RenameOptions.RenameInComments); m[RenameInStrings] = optionSet.GetOption(RenameOptions.RenameInStrings); m[RenameOverloads] = optionSet.GetOption(RenameOptions.RenameOverloads); m[Committed] = (outcome & UserActionOutcome.Committed) == UserActionOutcome.Committed; m[Canceled] = (outcome & UserActionOutcome.Canceled) == UserActionOutcome.Canceled; m[ConflictResolutionFinishedComputing] = conflictResolutionFinishedComputing; m[PreviewChanges] = previewChanges; m[RenamedIdentifiersWithoutConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.NoConflict); m[ResolvableReferenceConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.ResolvedReferenceConflict); m[ResolvableNonReferenceConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.ResolvedNonReferenceConflict); m[UnresolvableConflicts] = replacementKinds.Count(r => r == InlineRenameReplacementKind.UnresolvedConflict); }); } [Flags] public enum UserActionOutcome { Committed = 0x1, Canceled = 0x2, } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCompletionOptions { // Suppression due to https://github.com/dotnet/roslyn/issues/42614 public static PerLanguageOption<bool> BlockForCompletionItems { get; } = ((PerLanguageOption<bool>)Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems2)!; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCompletionOptions { // Suppression due to https://github.com/dotnet/roslyn/issues/42614 public static PerLanguageOption<bool> BlockForCompletionItems { get; } = ((PerLanguageOption<bool>)Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems2)!; } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/MoveToNamespace/VisualStudioMoveToNamespaceOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.MoveToNamespace; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.MoveToNamespace { [Export(typeof(IMoveToNamespaceOptionsService)), Shared] internal class VisualStudioMoveToNamespaceOptionsService : IMoveToNamespaceOptionsService { private const int HistorySize = 3; public readonly LinkedList<string> History = new(); private readonly Func<MoveToNamespaceDialogViewModel, bool?> _showDialog; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioMoveToNamespaceOptionsService() { _showDialog = viewModel => new MoveToNamespaceDialog(viewModel).ShowModal(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should be marked with 'ImportingConstructorAttribute'", Justification = "Test constructor")] internal VisualStudioMoveToNamespaceOptionsService(Func<MoveToNamespaceDialogViewModel, bool?> showDialog) { _showDialog = showDialog; } public MoveToNamespaceOptionsResult GetChangeNamespaceOptions( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFactsService) { var viewModel = new MoveToNamespaceDialogViewModel( defaultNamespace, availableNamespaces, syntaxFactsService, History.WhereNotNull().ToImmutableArray()); var result = _showDialog(viewModel); if (result == true) { OnSelected(viewModel.NamespaceName); return new MoveToNamespaceOptionsResult(viewModel.NamespaceName); } else { return MoveToNamespaceOptionsResult.Cancelled; } } private void OnSelected(string namespaceName) { History.Remove(namespaceName); History.AddFirst(namespaceName); if (History.Count > HistorySize) { History.RemoveLast(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.MoveToNamespace; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.MoveToNamespace { [Export(typeof(IMoveToNamespaceOptionsService)), Shared] internal class VisualStudioMoveToNamespaceOptionsService : IMoveToNamespaceOptionsService { private const int HistorySize = 3; public readonly LinkedList<string> History = new(); private readonly Func<MoveToNamespaceDialogViewModel, bool?> _showDialog; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioMoveToNamespaceOptionsService() { _showDialog = viewModel => new MoveToNamespaceDialog(viewModel).ShowModal(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should be marked with 'ImportingConstructorAttribute'", Justification = "Test constructor")] internal VisualStudioMoveToNamespaceOptionsService(Func<MoveToNamespaceDialogViewModel, bool?> showDialog) { _showDialog = showDialog; } public MoveToNamespaceOptionsResult GetChangeNamespaceOptions( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFactsService) { var viewModel = new MoveToNamespaceDialogViewModel( defaultNamespace, availableNamespaces, syntaxFactsService, History.WhereNotNull().ToImmutableArray()); var result = _showDialog(viewModel); if (result == true) { OnSelected(viewModel.NamespaceName); return new MoveToNamespaceOptionsResult(viewModel.NamespaceName); } else { return MoveToNamespaceOptionsResult.Cancelled; } } private void OnSelected(string namespaceName) { History.Remove(namespaceName); History.AddFirst(namespaceName); if (History.Count > HistorySize) { History.RemoveLast(); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public C() { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public C() { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public C() => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public C() { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public C() { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public C() => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigDocumentState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AnalyzerConfigDocumentState : TextDocumentState { private readonly ValueSource<AnalyzerConfig> _analyzerConfigValueSource; private AnalyzerConfigDocumentState( SolutionServices solutionServices, IDocumentServiceProvider documentServiceProvider, DocumentInfo.DocumentAttributes attributes, SourceText sourceTextOpt, ValueSource<TextAndVersion> textAndVersionSource) : base(solutionServices, documentServiceProvider, attributes, sourceTextOpt, textAndVersionSource) { _analyzerConfigValueSource = CreateAnalyzerConfigValueSource(); } public AnalyzerConfigDocumentState( DocumentInfo documentInfo, SolutionServices solutionServices) : base(documentInfo, solutionServices) { _analyzerConfigValueSource = CreateAnalyzerConfigValueSource(); } private ValueSource<AnalyzerConfig> CreateAnalyzerConfigValueSource() { return new AsyncLazy<AnalyzerConfig>( asynchronousComputeFunction: async cancellationToken => AnalyzerConfig.Parse(await GetTextAsync(cancellationToken).ConfigureAwait(false), FilePath), synchronousComputeFunction: cancellationToken => AnalyzerConfig.Parse(GetTextSynchronously(cancellationToken), FilePath), cacheResult: true); } public AnalyzerConfig GetAnalyzerConfig(CancellationToken cancellationToken) => _analyzerConfigValueSource.GetValue(cancellationToken); public Task<AnalyzerConfig> GetAnalyzerConfigAsync(CancellationToken cancellationToken) => _analyzerConfigValueSource.GetValueAsync(cancellationToken); public new AnalyzerConfigDocumentState UpdateText(TextLoader loader, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(loader, mode); public new AnalyzerConfigDocumentState UpdateText(SourceText text, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(text, mode); public new AnalyzerConfigDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(newTextAndVersion, mode); protected override TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental) { return new AnalyzerConfigDocumentState( this.solutionServices, this.Services, this.Attributes, this.sourceText, newTextSource); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AnalyzerConfigDocumentState : TextDocumentState { private readonly ValueSource<AnalyzerConfig> _analyzerConfigValueSource; private AnalyzerConfigDocumentState( SolutionServices solutionServices, IDocumentServiceProvider documentServiceProvider, DocumentInfo.DocumentAttributes attributes, SourceText sourceTextOpt, ValueSource<TextAndVersion> textAndVersionSource) : base(solutionServices, documentServiceProvider, attributes, sourceTextOpt, textAndVersionSource) { _analyzerConfigValueSource = CreateAnalyzerConfigValueSource(); } public AnalyzerConfigDocumentState( DocumentInfo documentInfo, SolutionServices solutionServices) : base(documentInfo, solutionServices) { _analyzerConfigValueSource = CreateAnalyzerConfigValueSource(); } private ValueSource<AnalyzerConfig> CreateAnalyzerConfigValueSource() { return new AsyncLazy<AnalyzerConfig>( asynchronousComputeFunction: async cancellationToken => AnalyzerConfig.Parse(await GetTextAsync(cancellationToken).ConfigureAwait(false), FilePath), synchronousComputeFunction: cancellationToken => AnalyzerConfig.Parse(GetTextSynchronously(cancellationToken), FilePath), cacheResult: true); } public AnalyzerConfig GetAnalyzerConfig(CancellationToken cancellationToken) => _analyzerConfigValueSource.GetValue(cancellationToken); public Task<AnalyzerConfig> GetAnalyzerConfigAsync(CancellationToken cancellationToken) => _analyzerConfigValueSource.GetValueAsync(cancellationToken); public new AnalyzerConfigDocumentState UpdateText(TextLoader loader, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(loader, mode); public new AnalyzerConfigDocumentState UpdateText(SourceText text, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(text, mode); public new AnalyzerConfigDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode) => (AnalyzerConfigDocumentState)base.UpdateText(newTextAndVersion, mode); protected override TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental) { return new AnalyzerConfigDocumentState( this.solutionServices, this.Services, this.Attributes, this.sourceText, newTextSource); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private abstract partial class CompilationAndGeneratorDriverTranslationAction { internal sealed class TouchDocumentAction : CompilationAndGeneratorDriverTranslationAction { private readonly DocumentState _oldState; private readonly DocumentState _newState; public TouchDocumentAction(DocumentState oldState, DocumentState newState) { _oldState = oldState; _newState = newState; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { return UpdateDocumentInCompilationAsync(oldCompilation, _oldState, _newState, cancellationToken); } public DocumentId DocumentId => _newState.Attributes.Id; // Replacing a single tree doesn't impact the generated trees in a compilation, so we can use this against // compilations that have generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override CompilationAndGeneratorDriverTranslationAction? TryMergeWithPrior(CompilationAndGeneratorDriverTranslationAction priorAction) { if (priorAction is TouchDocumentAction priorTouchAction && priorTouchAction._newState == _oldState) { return new TouchDocumentAction(priorTouchAction._oldState, _newState); } return null; } } internal sealed class TouchAdditionalDocumentAction : CompilationAndGeneratorDriverTranslationAction { private readonly AdditionalDocumentState _oldState; private readonly AdditionalDocumentState _newState; public TouchAdditionalDocumentAction(AdditionalDocumentState oldState, AdditionalDocumentState newState) { _oldState = oldState; _newState = newState; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override CompilationAndGeneratorDriverTranslationAction? TryMergeWithPrior(CompilationAndGeneratorDriverTranslationAction priorAction) { if (priorAction is TouchAdditionalDocumentAction priorTouchAction && priorTouchAction._newState == _oldState) { return new TouchAdditionalDocumentAction(priorTouchAction._oldState, _newState); } return null; } public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { var oldText = _oldState.AdditionalText; var newText = _newState.AdditionalText; return generatorDriver.ReplaceAdditionalText(oldText, newText); } } internal sealed class RemoveDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<DocumentState> _documents; public RemoveDocumentsAction(ImmutableArray<DocumentState> documents) { _documents = documents; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(_documents.Length); foreach (var document in _documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.RemoveSyntaxTrees(syntaxTrees); } // This action removes the specified trees, but leaves the generated trees untouched. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class AddDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<DocumentState> _documents; public AddDocumentsAction(ImmutableArray<DocumentState> documents) { _documents = documents; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(capacity: _documents.Length); foreach (var document in _documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.AddSyntaxTrees(syntaxTrees); } // This action adds the specified trees, but leaves the generated trees untouched. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class ReplaceAllSyntaxTreesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ProjectState _state; private readonly bool _isParseOptionChange; public ReplaceAllSyntaxTreesAction(ProjectState state, bool isParseOptionChange) { _state = state; _isParseOptionChange = isParseOptionChange; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(capacity: _state.DocumentStates.Count); foreach (var documentState in _state.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.RemoveAllSyntaxTrees().AddSyntaxTrees(syntaxTrees); } // Because this removes all trees, it'd also remove the generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => false; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { if (_isParseOptionChange) { RoslynDebug.AssertNotNull(_state.ParseOptions); return generatorDriver.WithUpdatedParseOptions(_state.ParseOptions); } else { // We are using this as a way to reorder syntax trees -- we don't need to do anything as the driver // will get the new compilation once we pass it to it. return generatorDriver; } } } internal sealed class ProjectCompilationOptionsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ProjectState _state; private readonly bool _isAnalyzerConfigChange; public ProjectCompilationOptionsAction(ProjectState state, bool isAnalyzerConfigChange) { _state = state; _isAnalyzerConfigChange = isAnalyzerConfigChange; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { RoslynDebug.AssertNotNull(_state.CompilationOptions); return Task.FromResult(oldCompilation.WithOptions(_state.CompilationOptions)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { if (_isAnalyzerConfigChange) { return generatorDriver.WithUpdatedAnalyzerConfigOptions(_state.AnalyzerOptions.AnalyzerConfigOptionsProvider); } else { // Changing any other option is fine and the driver can be reused. The driver // will get the new compilation once we pass it to it. return generatorDriver; } } } internal sealed class ProjectAssemblyNameAction : CompilationAndGeneratorDriverTranslationAction { private readonly string _assemblyName; public ProjectAssemblyNameAction(string assemblyName) { _assemblyName = assemblyName; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { return Task.FromResult(oldCompilation.WithAssemblyName(_assemblyName)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class AddAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AnalyzerReference> _analyzerReferences; private readonly string _language; public AddAnalyzerReferencesAction(ImmutableArray<AnalyzerReference> analyzerReferences, string language) { _analyzerReferences = analyzerReferences; _language = language; } // Changing analyzer references doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.AddGenerators(_analyzerReferences.SelectMany(r => r.GetGenerators(_language)).ToImmutableArray()); } } internal sealed class RemoveAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AnalyzerReference> _analyzerReferences; private readonly string _language; public RemoveAnalyzerReferencesAction(ImmutableArray<AnalyzerReference> analyzerReferences, string language) { _analyzerReferences = analyzerReferences; _language = language; } // Changing analyzer references doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.RemoveGenerators(_analyzerReferences.SelectMany(r => r.GetGenerators(_language)).ToImmutableArray()); } } internal sealed class AddAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AdditionalDocumentState> _additionalDocuments; public AddAdditionalDocumentsAction(ImmutableArray<AdditionalDocumentState> additionalDocuments) { _additionalDocuments = additionalDocuments; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.AddAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } internal sealed class RemoveAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AdditionalDocumentState> _additionalDocuments; public RemoveAdditionalDocumentsAction(ImmutableArray<AdditionalDocumentState> additionalDocuments) { _additionalDocuments = additionalDocuments; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.RemoveAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private abstract partial class CompilationAndGeneratorDriverTranslationAction { internal sealed class TouchDocumentAction : CompilationAndGeneratorDriverTranslationAction { private readonly DocumentState _oldState; private readonly DocumentState _newState; public TouchDocumentAction(DocumentState oldState, DocumentState newState) { _oldState = oldState; _newState = newState; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { return UpdateDocumentInCompilationAsync(oldCompilation, _oldState, _newState, cancellationToken); } public DocumentId DocumentId => _newState.Attributes.Id; // Replacing a single tree doesn't impact the generated trees in a compilation, so we can use this against // compilations that have generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override CompilationAndGeneratorDriverTranslationAction? TryMergeWithPrior(CompilationAndGeneratorDriverTranslationAction priorAction) { if (priorAction is TouchDocumentAction priorTouchAction && priorTouchAction._newState == _oldState) { return new TouchDocumentAction(priorTouchAction._oldState, _newState); } return null; } } internal sealed class TouchAdditionalDocumentAction : CompilationAndGeneratorDriverTranslationAction { private readonly AdditionalDocumentState _oldState; private readonly AdditionalDocumentState _newState; public TouchAdditionalDocumentAction(AdditionalDocumentState oldState, AdditionalDocumentState newState) { _oldState = oldState; _newState = newState; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override CompilationAndGeneratorDriverTranslationAction? TryMergeWithPrior(CompilationAndGeneratorDriverTranslationAction priorAction) { if (priorAction is TouchAdditionalDocumentAction priorTouchAction && priorTouchAction._newState == _oldState) { return new TouchAdditionalDocumentAction(priorTouchAction._oldState, _newState); } return null; } public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { var oldText = _oldState.AdditionalText; var newText = _newState.AdditionalText; return generatorDriver.ReplaceAdditionalText(oldText, newText); } } internal sealed class RemoveDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<DocumentState> _documents; public RemoveDocumentsAction(ImmutableArray<DocumentState> documents) { _documents = documents; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(_documents.Length); foreach (var document in _documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.RemoveSyntaxTrees(syntaxTrees); } // This action removes the specified trees, but leaves the generated trees untouched. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class AddDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<DocumentState> _documents; public AddDocumentsAction(ImmutableArray<DocumentState> documents) { _documents = documents; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(capacity: _documents.Length); foreach (var document in _documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.AddSyntaxTrees(syntaxTrees); } // This action adds the specified trees, but leaves the generated trees untouched. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class ReplaceAllSyntaxTreesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ProjectState _state; private readonly bool _isParseOptionChange; public ReplaceAllSyntaxTreesAction(ProjectState state, bool isParseOptionChange) { _state = state; _isParseOptionChange = isParseOptionChange; } public override async Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { var syntaxTrees = new List<SyntaxTree>(capacity: _state.DocumentStates.Count); foreach (var documentState in _state.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } return oldCompilation.RemoveAllSyntaxTrees().AddSyntaxTrees(syntaxTrees); } // Because this removes all trees, it'd also remove the generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => false; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { if (_isParseOptionChange) { RoslynDebug.AssertNotNull(_state.ParseOptions); return generatorDriver.WithUpdatedParseOptions(_state.ParseOptions); } else { // We are using this as a way to reorder syntax trees -- we don't need to do anything as the driver // will get the new compilation once we pass it to it. return generatorDriver; } } } internal sealed class ProjectCompilationOptionsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ProjectState _state; private readonly bool _isAnalyzerConfigChange; public ProjectCompilationOptionsAction(ProjectState state, bool isAnalyzerConfigChange) { _state = state; _isAnalyzerConfigChange = isAnalyzerConfigChange; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { RoslynDebug.AssertNotNull(_state.CompilationOptions); return Task.FromResult(oldCompilation.WithOptions(_state.CompilationOptions)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { if (_isAnalyzerConfigChange) { return generatorDriver.WithUpdatedAnalyzerConfigOptions(_state.AnalyzerOptions.AnalyzerConfigOptionsProvider); } else { // Changing any other option is fine and the driver can be reused. The driver // will get the new compilation once we pass it to it. return generatorDriver; } } } internal sealed class ProjectAssemblyNameAction : CompilationAndGeneratorDriverTranslationAction { private readonly string _assemblyName; public ProjectAssemblyNameAction(string assemblyName) { _assemblyName = assemblyName; } public override Task<Compilation> TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { return Task.FromResult(oldCompilation.WithAssemblyName(_assemblyName)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } internal sealed class AddAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AnalyzerReference> _analyzerReferences; private readonly string _language; public AddAnalyzerReferencesAction(ImmutableArray<AnalyzerReference> analyzerReferences, string language) { _analyzerReferences = analyzerReferences; _language = language; } // Changing analyzer references doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.AddGenerators(_analyzerReferences.SelectMany(r => r.GetGenerators(_language)).ToImmutableArray()); } } internal sealed class RemoveAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AnalyzerReference> _analyzerReferences; private readonly string _language; public RemoveAnalyzerReferencesAction(ImmutableArray<AnalyzerReference> analyzerReferences, string language) { _analyzerReferences = analyzerReferences; _language = language; } // Changing analyzer references doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.RemoveGenerators(_analyzerReferences.SelectMany(r => r.GetGenerators(_language)).ToImmutableArray()); } } internal sealed class AddAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AdditionalDocumentState> _additionalDocuments; public AddAdditionalDocumentsAction(ImmutableArray<AdditionalDocumentState> additionalDocuments) { _additionalDocuments = additionalDocuments; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.AddAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } internal sealed class RemoveAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction { private readonly ImmutableArray<AdditionalDocumentState> _additionalDocuments; public RemoveAdditionalDocumentsAction(ImmutableArray<AdditionalDocumentState> additionalDocuments) { _additionalDocuments = additionalDocuments; } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping // the compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { return generatorDriver.RemoveAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Text/CompositeText.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// A composite of a sequence of <see cref="SourceText"/>s. /// </summary> internal sealed class CompositeText : SourceText { private readonly ImmutableArray<SourceText> _segments; private readonly int _length; private readonly int _storageSize; private readonly int[] _segmentOffsets; private readonly Encoding? _encoding; private CompositeText(ImmutableArray<SourceText> segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { Debug.Assert(!segments.IsDefaultOrEmpty); _segments = segments; _encoding = encoding; ComputeLengthAndStorageSize(segments, out _length, out _storageSize); _segmentOffsets = new int[segments.Length]; int offset = 0; for (int i = 0; i < _segmentOffsets.Length; i++) { _segmentOffsets[i] = offset; offset += _segments[i].Length; } } public override Encoding? Encoding { get { return _encoding; } } public override int Length { get { return _length; } } internal override int StorageSize { get { return _storageSize; } } internal override ImmutableArray<SourceText> Segments { get { return _segments; } } public override char this[int position] { get { int index; int offset; GetIndexAndOffset(position, out index, out offset); return _segments[index][offset]; } } public override SourceText GetSubText(TextSpan span) { CheckSubSpan(span); var sourceIndex = span.Start; var count = span.Length; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); var newSegments = ArrayBuilder<SourceText>.GetInstance(); try { while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); AddSegments(newSegments, segment.GetSubText(new TextSpan(segOffset, copyLength))); count -= copyLength; segIndex++; segOffset = 0; } return ToSourceText(newSegments, this, adjustSegments: false); } finally { newSegments.Free(); } } private void GetIndexAndOffset(int position, out int index, out int offset) { // Binary search to find the chunk that contains the given position. int idx = _segmentOffsets.BinarySearch(position); index = idx >= 0 ? idx : (~idx - 1); offset = position - _segmentOffsets[index]; } /// <summary> /// Validates the arguments passed to <see cref="CopyTo"/> against the published contract. /// </summary> /// <returns>True if should bother to proceed with copying.</returns> private bool CheckCopyToArguments(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); if (destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); if (count < 0 || count > this.Length - sourceIndex || count > destination.Length - destinationIndex) throw new ArgumentOutOfRangeException(nameof(count)); return count > 0; } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (!CheckCopyToArguments(sourceIndex, destination, destinationIndex, count)) return; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); segment.CopyTo(segOffset, destination, destinationIndex, copyLength); count -= copyLength; destinationIndex += copyLength; segIndex++; segOffset = 0; } } internal static void AddSegments(ArrayBuilder<SourceText> segments, SourceText text) { CompositeText? composite = text as CompositeText; if (composite == null) { segments.Add(text); } else { segments.AddRange(composite._segments); } } internal static SourceText ToSourceText(ArrayBuilder<SourceText> segments, SourceText original, bool adjustSegments) { if (adjustSegments) { TrimInaccessibleText(segments); ReduceSegmentCountIfNecessary(segments); } if (segments.Count == 0) { return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm); } else if (segments.Count == 1) { return segments[0]; } else { return new CompositeText(segments.ToImmutable(), original.Encoding, original.ChecksumAlgorithm); } } // both of these numbers are currently arbitrary. internal const int TARGET_SEGMENT_COUNT_AFTER_REDUCTION = 32; internal const int MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION = 64; /// <summary> /// Reduces the number of segments toward the target number of segments, /// if the number of segments is deemed to be too large (beyond the maximum). /// </summary> private static void ReduceSegmentCountIfNecessary(ArrayBuilder<SourceText> segments) { if (segments.Count > MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION) { var segmentSize = GetMinimalSegmentSizeToUseForCombining(segments); CombineSegments(segments, segmentSize); } } // Allow combining segments if each has a size less than or equal to this amount. // This is some arbitrary number deemed to be small private const int INITIAL_SEGMENT_SIZE_FOR_COMBINING = 32; // Segments must be less than (or equal) to this size to be combined with other segments. // This is some arbitrary number that is a fraction of max int. private const int MAXIMUM_SEGMENT_SIZE_FOR_COMBINING = int.MaxValue / 16; /// <summary> /// Determines the segment size to use for call to CombineSegments, that will result in the segment count /// being reduced to less than or equal to the target segment count. /// </summary> private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder<SourceText> segments) { // find the minimal segment size that reduces enough segments to less that or equal to the ideal segment count for (var segmentSize = INITIAL_SEGMENT_SIZE_FOR_COMBINING; segmentSize <= MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; segmentSize *= 2) { if (GetSegmentCountIfCombined(segments, segmentSize) <= TARGET_SEGMENT_COUNT_AFTER_REDUCTION) { return segmentSize; } } return MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; } /// <summary> /// Determines the segment count that would result if the segments of size less than or equal to /// the specified segment size were to be combined. /// </summary> private static int GetSegmentCountIfCombined(ArrayBuilder<SourceText> segments, int segmentSize) { int numberOfSegmentsReduced = 0; for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { // count how many contiguous segments can be combined int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; } } if (count > 1) { var removed = count - 1; numberOfSegmentsReduced += removed; i += removed; } } } return segments.Count - numberOfSegmentsReduced; } /// <summary> /// Combines contiguous segments with lengths that are each less than or equal to the specified segment size. /// </summary> private static void CombineSegments(ArrayBuilder<SourceText> segments, int segmentSize) { for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { int combinedLength = segments[i].Length; // count how many contiguous segments are reducible int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; combinedLength += segments[j].Length; } } // if we've got at least two, then combine them into a single text if (count > 1) { var encoding = segments[i].Encoding; var algorithm = segments[i].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, combinedLength); while (count > 0) { segments[i].Write(writer); segments.RemoveAt(i); count--; } var newText = writer.ToSourceText(); segments.Insert(i, newText); } } } } private static readonly ObjectPool<HashSet<SourceText>> s_uniqueSourcesPool = new ObjectPool<HashSet<SourceText>>(() => new HashSet<SourceText>(), 5); /// <summary> /// Compute total text length and total size of storage buffers held /// </summary> private static void ComputeLengthAndStorageSize(IReadOnlyList<SourceText> segments, out int length, out int size) { var uniqueSources = s_uniqueSourcesPool.Allocate(); length = 0; for (int i = 0; i < segments.Count; i++) { var segment = segments[i]; length += segment.Length; uniqueSources.Add(segment.StorageKey); } size = 0; foreach (var segment in uniqueSources) { size += segment.StorageSize; } uniqueSources.Clear(); s_uniqueSourcesPool.Free(uniqueSources); } /// <summary> /// Trim excessive inaccessible text. /// </summary> private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments) { int length, size; ComputeLengthAndStorageSize(segments, out length, out size); // if more than half of the storage is unused, compress into a single new segment if (length < size / 2) { var encoding = segments[0].Encoding; var algorithm = segments[0].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, length); foreach (var segment in segments) { segment.Write(writer); } segments.Clear(); segments.Add(writer.ToSourceText()); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// A composite of a sequence of <see cref="SourceText"/>s. /// </summary> internal sealed class CompositeText : SourceText { private readonly ImmutableArray<SourceText> _segments; private readonly int _length; private readonly int _storageSize; private readonly int[] _segmentOffsets; private readonly Encoding? _encoding; private CompositeText(ImmutableArray<SourceText> segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { Debug.Assert(!segments.IsDefaultOrEmpty); _segments = segments; _encoding = encoding; ComputeLengthAndStorageSize(segments, out _length, out _storageSize); _segmentOffsets = new int[segments.Length]; int offset = 0; for (int i = 0; i < _segmentOffsets.Length; i++) { _segmentOffsets[i] = offset; offset += _segments[i].Length; } } public override Encoding? Encoding { get { return _encoding; } } public override int Length { get { return _length; } } internal override int StorageSize { get { return _storageSize; } } internal override ImmutableArray<SourceText> Segments { get { return _segments; } } public override char this[int position] { get { int index; int offset; GetIndexAndOffset(position, out index, out offset); return _segments[index][offset]; } } public override SourceText GetSubText(TextSpan span) { CheckSubSpan(span); var sourceIndex = span.Start; var count = span.Length; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); var newSegments = ArrayBuilder<SourceText>.GetInstance(); try { while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); AddSegments(newSegments, segment.GetSubText(new TextSpan(segOffset, copyLength))); count -= copyLength; segIndex++; segOffset = 0; } return ToSourceText(newSegments, this, adjustSegments: false); } finally { newSegments.Free(); } } private void GetIndexAndOffset(int position, out int index, out int offset) { // Binary search to find the chunk that contains the given position. int idx = _segmentOffsets.BinarySearch(position); index = idx >= 0 ? idx : (~idx - 1); offset = position - _segmentOffsets[index]; } /// <summary> /// Validates the arguments passed to <see cref="CopyTo"/> against the published contract. /// </summary> /// <returns>True if should bother to proceed with copying.</returns> private bool CheckCopyToArguments(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); if (destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); if (count < 0 || count > this.Length - sourceIndex || count > destination.Length - destinationIndex) throw new ArgumentOutOfRangeException(nameof(count)); return count > 0; } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (!CheckCopyToArguments(sourceIndex, destination, destinationIndex, count)) return; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); segment.CopyTo(segOffset, destination, destinationIndex, copyLength); count -= copyLength; destinationIndex += copyLength; segIndex++; segOffset = 0; } } internal static void AddSegments(ArrayBuilder<SourceText> segments, SourceText text) { CompositeText? composite = text as CompositeText; if (composite == null) { segments.Add(text); } else { segments.AddRange(composite._segments); } } internal static SourceText ToSourceText(ArrayBuilder<SourceText> segments, SourceText original, bool adjustSegments) { if (adjustSegments) { TrimInaccessibleText(segments); ReduceSegmentCountIfNecessary(segments); } if (segments.Count == 0) { return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm); } else if (segments.Count == 1) { return segments[0]; } else { return new CompositeText(segments.ToImmutable(), original.Encoding, original.ChecksumAlgorithm); } } // both of these numbers are currently arbitrary. internal const int TARGET_SEGMENT_COUNT_AFTER_REDUCTION = 32; internal const int MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION = 64; /// <summary> /// Reduces the number of segments toward the target number of segments, /// if the number of segments is deemed to be too large (beyond the maximum). /// </summary> private static void ReduceSegmentCountIfNecessary(ArrayBuilder<SourceText> segments) { if (segments.Count > MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION) { var segmentSize = GetMinimalSegmentSizeToUseForCombining(segments); CombineSegments(segments, segmentSize); } } // Allow combining segments if each has a size less than or equal to this amount. // This is some arbitrary number deemed to be small private const int INITIAL_SEGMENT_SIZE_FOR_COMBINING = 32; // Segments must be less than (or equal) to this size to be combined with other segments. // This is some arbitrary number that is a fraction of max int. private const int MAXIMUM_SEGMENT_SIZE_FOR_COMBINING = int.MaxValue / 16; /// <summary> /// Determines the segment size to use for call to CombineSegments, that will result in the segment count /// being reduced to less than or equal to the target segment count. /// </summary> private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder<SourceText> segments) { // find the minimal segment size that reduces enough segments to less that or equal to the ideal segment count for (var segmentSize = INITIAL_SEGMENT_SIZE_FOR_COMBINING; segmentSize <= MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; segmentSize *= 2) { if (GetSegmentCountIfCombined(segments, segmentSize) <= TARGET_SEGMENT_COUNT_AFTER_REDUCTION) { return segmentSize; } } return MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; } /// <summary> /// Determines the segment count that would result if the segments of size less than or equal to /// the specified segment size were to be combined. /// </summary> private static int GetSegmentCountIfCombined(ArrayBuilder<SourceText> segments, int segmentSize) { int numberOfSegmentsReduced = 0; for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { // count how many contiguous segments can be combined int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; } } if (count > 1) { var removed = count - 1; numberOfSegmentsReduced += removed; i += removed; } } } return segments.Count - numberOfSegmentsReduced; } /// <summary> /// Combines contiguous segments with lengths that are each less than or equal to the specified segment size. /// </summary> private static void CombineSegments(ArrayBuilder<SourceText> segments, int segmentSize) { for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { int combinedLength = segments[i].Length; // count how many contiguous segments are reducible int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; combinedLength += segments[j].Length; } } // if we've got at least two, then combine them into a single text if (count > 1) { var encoding = segments[i].Encoding; var algorithm = segments[i].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, combinedLength); while (count > 0) { segments[i].Write(writer); segments.RemoveAt(i); count--; } var newText = writer.ToSourceText(); segments.Insert(i, newText); } } } } private static readonly ObjectPool<HashSet<SourceText>> s_uniqueSourcesPool = new ObjectPool<HashSet<SourceText>>(() => new HashSet<SourceText>(), 5); /// <summary> /// Compute total text length and total size of storage buffers held /// </summary> private static void ComputeLengthAndStorageSize(IReadOnlyList<SourceText> segments, out int length, out int size) { var uniqueSources = s_uniqueSourcesPool.Allocate(); length = 0; for (int i = 0; i < segments.Count; i++) { var segment = segments[i]; length += segment.Length; uniqueSources.Add(segment.StorageKey); } size = 0; foreach (var segment in uniqueSources) { size += segment.StorageSize; } uniqueSources.Clear(); s_uniqueSourcesPool.Free(uniqueSources); } /// <summary> /// Trim excessive inaccessible text. /// </summary> private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments) { int length, size; ComputeLengthAndStorageSize(segments, out length, out size); // if more than half of the storage is unused, compress into a single new segment if (length < size / 2) { var encoding = segments[0].Encoding; var algorithm = segments[0].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, length); foreach (var segment in segments) { segment.Write(writer); } segments.Clear(); segments.Add(writer.ToSourceText()); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Completion/CharacterSetModificationRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// A rule that modifies a set of characters. /// </summary> public readonly struct CharacterSetModificationRule { /// <summary> /// The kind of modification. /// </summary> public CharacterSetModificationKind Kind { get; } /// <summary> /// One or more characters. /// </summary> public ImmutableArray<char> Characters { get; } private CharacterSetModificationRule(CharacterSetModificationKind kind, ImmutableArray<char> characters) { Kind = kind; Characters = characters; } /// <summary> /// Creates a new <see cref="CharacterSetModificationRule"/> instance. /// </summary> /// <param name="kind">The kind of rule.</param> /// <param name="characters">One or more characters. These are typically punctuation characters.</param> /// <returns></returns> public static CharacterSetModificationRule Create(CharacterSetModificationKind kind, ImmutableArray<char> characters) => new(kind, characters); /// <summary> /// Creates a new <see cref="CharacterSetModificationRule"/> instance. /// </summary> /// <param name="kind">The kind of rule.</param> /// <param name="characters">One or more characters. These are typically punctuation characters.</param> /// <returns></returns> public static CharacterSetModificationRule Create(CharacterSetModificationKind kind, params char[] characters) => new(kind, characters.ToImmutableArray()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// A rule that modifies a set of characters. /// </summary> public readonly struct CharacterSetModificationRule { /// <summary> /// The kind of modification. /// </summary> public CharacterSetModificationKind Kind { get; } /// <summary> /// One or more characters. /// </summary> public ImmutableArray<char> Characters { get; } private CharacterSetModificationRule(CharacterSetModificationKind kind, ImmutableArray<char> characters) { Kind = kind; Characters = characters; } /// <summary> /// Creates a new <see cref="CharacterSetModificationRule"/> instance. /// </summary> /// <param name="kind">The kind of rule.</param> /// <param name="characters">One or more characters. These are typically punctuation characters.</param> /// <returns></returns> public static CharacterSetModificationRule Create(CharacterSetModificationKind kind, ImmutableArray<char> characters) => new(kind, characters); /// <summary> /// Creates a new <see cref="CharacterSetModificationRule"/> instance. /// </summary> /// <param name="kind">The kind of rule.</param> /// <param name="characters">One or more characters. These are typically punctuation characters.</param> /// <returns></returns> public static CharacterSetModificationRule Create(CharacterSetModificationKind kind, params char[] characters) => new(kind, characters.ToImmutableArray()); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/CSharp/Portable/FindSymbols/CSharpDeclaredSymbolInfoFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Cache FileCodeModel instances for a given project (we are using WeakReference for now, /// so that we can more or less match the semantics of the former native implementation, which /// offered reference equality until all instances were collected by the GC) /// </summary> internal sealed partial class CodeModelProjectCache { private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly ICodeModelInstanceFactory _codeModelInstanceFactory; private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly object _cacheGate = new object(); private EnvDTE.CodeModel _rootCodeModel; private bool _zombied; internal CodeModelProjectCache(IThreadingContext threadingContext, ProjectId projectId, ICodeModelInstanceFactory codeModelInstanceFactory, ProjectCodeModelFactory projectFactory, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace) { _state = new CodeModelState(threadingContext, serviceProvider, languageServices, workspace, projectFactory); _projectId = projectId; _codeModelInstanceFactory = codeModelInstanceFactory; } /// <summary> /// Look for an existing instance of FileCodeModel in our cache. /// Return null if there is no active FCM for "fileName". /// </summary> private CacheEntry? GetCacheEntry(string fileName) { lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { return cacheEntry; } } return null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // This ultimately ends up calling GetOrCreateFileCodeModel(fileName, parent) with the correct "parent" object // through the project system. var newFileCodeModel = (EnvDTE80.FileCodeModel2)_codeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(filePath); return new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(newFileCodeModel); } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? GetComHandleForFileCodeModel(string filePath) { var cacheEntry = GetCacheEntry(filePath); return cacheEntry?.ComHandle; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // Check that we know about this file! var documentId = _state.Workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).Where(id => id.ProjectId == _projectId).FirstOrDefault(); if (documentId == null) { // Matches behavior of native (C#) implementation throw Exceptions.ThrowENotImpl(); } // Create object (outside of lock) var newFileCodeModel = FileCodeModel.Create(_state, parent, documentId, new TextManagerAdapter()); var newCacheEntry = new CacheEntry(newFileCodeModel); // Second try (object might have been added by another thread at this point!) lock (_cacheGate) { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } // Note: Using the indexer here (instead of "Add") is relevant since the old // WeakReference entry is likely still in the cache (with a Null target, of course) _cache[filePath] = newCacheEntry; return newFileCodeModel; } } public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) { if (_zombied) { Debug.Fail("Cannot access root code model after code model was shutdown!"); throw Exceptions.ThrowEUnexpected(); } if (_rootCodeModel == null) { _rootCodeModel = RootCodeModel.Create(_state, parent, _projectId); } return _rootCodeModel; } public IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetFileCodeModelInstances() { var result = new List<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>>(); lock (_cacheGate) { foreach (var cacheEntry in _cache.Values) { var comHandle = cacheEntry.ComHandle; if (comHandle != null) { result.Add(comHandle.Value); } } } return result; } public void OnProjectClosed() { var instances = GetFileCodeModelInstances(); lock (_cacheGate) { _cache.Clear(); } foreach (var instance in instances) { instance.Object.Shutdown(); } _zombied = true; } public void OnSourceFileRemoved(string fileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null; lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { comHandle = cacheEntry.ComHandle; _cache.Remove(fileName); } } if (comHandle != null) { comHandle.Value.Object.Shutdown(); } } public void OnSourceFileRenaming(string oldFileName, string newFileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToRename = null; ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToShutDown = null; lock (_cacheGate) { if (_cache.TryGetValue(oldFileName, out var cacheEntry)) { comHandleToRename = cacheEntry.ComHandle; _cache.Remove(oldFileName); if (comHandleToRename != null) { // We might already have a code model for this new filename. This can happen if // we were to rename Goo.cs to Goocs, which will call this method, and then rename // it back, which does not call this method. This results in both Goo.cs and Goocs // being in the cache. We could fix that "correctly", but the zombied Goocs code model // is pretty broken, so there's no point in trying to reuse it. if (_cache.TryGetValue(newFileName, out cacheEntry)) { comHandleToShutDown = cacheEntry.ComHandle; } _cache.Add(newFileName, cacheEntry); } } } comHandleToShutDown?.Object.Shutdown(); comHandleToRename?.Object.OnRename(newFileName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Cache FileCodeModel instances for a given project (we are using WeakReference for now, /// so that we can more or less match the semantics of the former native implementation, which /// offered reference equality until all instances were collected by the GC) /// </summary> internal sealed partial class CodeModelProjectCache { private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly ICodeModelInstanceFactory _codeModelInstanceFactory; private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly object _cacheGate = new object(); private EnvDTE.CodeModel _rootCodeModel; private bool _zombied; internal CodeModelProjectCache(IThreadingContext threadingContext, ProjectId projectId, ICodeModelInstanceFactory codeModelInstanceFactory, ProjectCodeModelFactory projectFactory, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace) { _state = new CodeModelState(threadingContext, serviceProvider, languageServices, workspace, projectFactory); _projectId = projectId; _codeModelInstanceFactory = codeModelInstanceFactory; } /// <summary> /// Look for an existing instance of FileCodeModel in our cache. /// Return null if there is no active FCM for "fileName". /// </summary> private CacheEntry? GetCacheEntry(string fileName) { lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { return cacheEntry; } } return null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // This ultimately ends up calling GetOrCreateFileCodeModel(fileName, parent) with the correct "parent" object // through the project system. var newFileCodeModel = (EnvDTE80.FileCodeModel2)_codeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(filePath); return new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(newFileCodeModel); } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? GetComHandleForFileCodeModel(string filePath) { var cacheEntry = GetCacheEntry(filePath); return cacheEntry?.ComHandle; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // Check that we know about this file! var documentId = _state.Workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).Where(id => id.ProjectId == _projectId).FirstOrDefault(); if (documentId == null) { // Matches behavior of native (C#) implementation throw Exceptions.ThrowENotImpl(); } // Create object (outside of lock) var newFileCodeModel = FileCodeModel.Create(_state, parent, documentId, new TextManagerAdapter()); var newCacheEntry = new CacheEntry(newFileCodeModel); // Second try (object might have been added by another thread at this point!) lock (_cacheGate) { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } // Note: Using the indexer here (instead of "Add") is relevant since the old // WeakReference entry is likely still in the cache (with a Null target, of course) _cache[filePath] = newCacheEntry; return newFileCodeModel; } } public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) { if (_zombied) { Debug.Fail("Cannot access root code model after code model was shutdown!"); throw Exceptions.ThrowEUnexpected(); } if (_rootCodeModel == null) { _rootCodeModel = RootCodeModel.Create(_state, parent, _projectId); } return _rootCodeModel; } public IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetFileCodeModelInstances() { var result = new List<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>>(); lock (_cacheGate) { foreach (var cacheEntry in _cache.Values) { var comHandle = cacheEntry.ComHandle; if (comHandle != null) { result.Add(comHandle.Value); } } } return result; } public void OnProjectClosed() { var instances = GetFileCodeModelInstances(); lock (_cacheGate) { _cache.Clear(); } foreach (var instance in instances) { instance.Object.Shutdown(); } _zombied = true; } public void OnSourceFileRemoved(string fileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null; lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { comHandle = cacheEntry.ComHandle; _cache.Remove(fileName); } } if (comHandle != null) { comHandle.Value.Object.Shutdown(); } } public void OnSourceFileRenaming(string oldFileName, string newFileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToRename = null; ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToShutDown = null; lock (_cacheGate) { if (_cache.TryGetValue(oldFileName, out var cacheEntry)) { comHandleToRename = cacheEntry.ComHandle; _cache.Remove(oldFileName); if (comHandleToRename != null) { // We might already have a code model for this new filename. This can happen if // we were to rename Goo.cs to Goocs, which will call this method, and then rename // it back, which does not call this method. This results in both Goo.cs and Goocs // being in the cache. We could fix that "correctly", but the zombied Goocs code model // is pretty broken, so there's no point in trying to reuse it. if (_cache.TryGetValue(newFileName, out cacheEntry)) { comHandleToShutDown = cacheEntry.ComHandle; } _cache.Add(newFileName, cacheEntry); } } } comHandleToShutDown?.Object.Shutdown(); comHandleToRename?.Object.OnRename(newFileName); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Xaml/Impl/Diagnostics/XamlDiagnosticIds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics { internal static class XamlDiagnosticIds { public const string UnnecessaryNamespacesId = "XAML1103"; public const string MissingNamespaceId = "XAML0002"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics { internal static class XamlDiagnosticIds { public const string UnnecessaryNamespacesId = "XAML1103"; public const string MissingNamespaceId = "XAML0002"; } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/Venus/IVsContainedLanguageCodeSupport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetMembers and GetCompatibleEventMembers, because they take optional out /// params, and the marshalling was wrong in the PIA. /// </summary> [ComImport, ComConversionLoss, InterfaceType(1), Guid("F386BE91-0E80-43AF-8EB6-8B829FA06282")] internal interface IVsContainedLanguageCodeSupport { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int CreateUniqueEventName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventHandlerName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMemberNavigationPoint( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanNavPoint, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] out uint pItemID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMembers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwFlags, out int pcMembers, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int OnRenamed( [In, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.ContainedLanguageRenameType")] ContainedLanguageRenameType clrt, [In, MarshalAs(UnmanagedType.BStr)] string bstrOldID, [In, MarshalAs(UnmanagedType.BStr)] string bstrNewID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int IsValidID( [In, MarshalAs(UnmanagedType.BStr)] string bstrID, out bool pfIsValidID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetBaseClassName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [MarshalAs(UnmanagedType.BStr)] out string pbstrBaseClassName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetEventHandlerMemberID( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetCompatibleEventHandlers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, out int pcMembers, IntPtr ppbstrEventHandlerNames, IntPtr ppbstrMemberIDs); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetMembers and GetCompatibleEventMembers, because they take optional out /// params, and the marshalling was wrong in the PIA. /// </summary> [ComImport, ComConversionLoss, InterfaceType(1), Guid("F386BE91-0E80-43AF-8EB6-8B829FA06282")] internal interface IVsContainedLanguageCodeSupport { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int CreateUniqueEventName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventHandlerName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMemberNavigationPoint( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanNavPoint, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] out uint pItemID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMembers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwFlags, out int pcMembers, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int OnRenamed( [In, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.ContainedLanguageRenameType")] ContainedLanguageRenameType clrt, [In, MarshalAs(UnmanagedType.BStr)] string bstrOldID, [In, MarshalAs(UnmanagedType.BStr)] string bstrNewID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int IsValidID( [In, MarshalAs(UnmanagedType.BStr)] string bstrID, out bool pfIsValidID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetBaseClassName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [MarshalAs(UnmanagedType.BStr)] out string pbstrBaseClassName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetEventHandlerMemberID( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetCompatibleEventHandlers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, out int pcMembers, IntPtr ppbstrEventHandlerNames, IntPtr ppbstrMemberIDs); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/CodeFixes/AddExplicitCast/InheritanceDistanceComparer.cs
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class GlyphExtensions { // hardcode ImageCatalogGuid locally rather than calling KnownImageIds.ImageCatalogGuid // So it doesnot have dependency for Microsoft.VisualStudio.ImageCatalog.dll // https://github.com/dotnet/roslyn/issues/26642 private static readonly Guid ImageCatalogGuid = Guid.Parse("ae27a6b0-e345-4288-96df-5eaf394ee369"); public static ImageId GetImageCatalogImageId(int imageId) => new(ImageCatalogGuid, imageId); public static ImageId GetImageId(this Glyph glyph) { // VS for mac cannot refer to ImageMoniker // so we need to expose ImageId instead of ImageMoniker here // and expose ImageMoniker in the EditorFeatures.wpf.dll // The use of constants here is okay because the compiler inlines their values, so no runtime reference is needed. // There are tests in src\EditorFeatures\Test\AssemblyReferenceTests.cs to ensure we don't regress that. switch (glyph) { case Glyph.None: return default; case Glyph.Assembly: return new ImageId(ImageCatalogGuid, KnownImageIds.Assembly); case Glyph.BasicFile: return new ImageId(ImageCatalogGuid, KnownImageIds.VBFileNode); case Glyph.BasicProject: return new ImageId(ImageCatalogGuid, KnownImageIds.VBProjectNode); case Glyph.ClassPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPublic); case Glyph.ClassProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassProtected); case Glyph.ClassPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPrivate); case Glyph.ClassInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassInternal); case Glyph.CSharpFile: return new ImageId(ImageCatalogGuid, KnownImageIds.CSFileNode); case Glyph.CSharpProject: return new ImageId(ImageCatalogGuid, KnownImageIds.CSProjectNode); case Glyph.ConstantPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPublic); case Glyph.ConstantProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantProtected); case Glyph.ConstantPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPrivate); case Glyph.ConstantInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantInternal); case Glyph.DelegatePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePublic); case Glyph.DelegateProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateProtected); case Glyph.DelegatePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePrivate); case Glyph.DelegateInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateInternal); case Glyph.EnumPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPublic); case Glyph.EnumProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationProtected); case Glyph.EnumPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPrivate); case Glyph.EnumInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationInternal); case Glyph.EnumMemberPublic: case Glyph.EnumMemberProtected: case Glyph.EnumMemberPrivate: case Glyph.EnumMemberInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationItemPublic); case Glyph.Error: return new ImageId(ImageCatalogGuid, KnownImageIds.StatusError); case Glyph.EventPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.EventPublic); case Glyph.EventProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.EventProtected); case Glyph.EventPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.EventPrivate); case Glyph.EventInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EventInternal); // Extension methods have the same glyph regardless of accessibility. case Glyph.ExtensionMethodPublic: case Glyph.ExtensionMethodProtected: case Glyph.ExtensionMethodPrivate: case Glyph.ExtensionMethodInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ExtensionMethod); case Glyph.FieldPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic); case Glyph.FieldProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldProtected); case Glyph.FieldPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPrivate); case Glyph.FieldInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldInternal); case Glyph.InterfacePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePublic); case Glyph.InterfaceProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceProtected); case Glyph.InterfacePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePrivate); case Glyph.InterfaceInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceInternal); // TODO: Figure out the right thing to return here. case Glyph.Intrinsic: return new ImageId(ImageCatalogGuid, KnownImageIds.Type); case Glyph.Keyword: return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseKeyword); case Glyph.Label: return new ImageId(ImageCatalogGuid, KnownImageIds.Label); case Glyph.Parameter: case Glyph.Local: return new ImageId(ImageCatalogGuid, KnownImageIds.LocalVariable); case Glyph.Namespace: return new ImageId(ImageCatalogGuid, KnownImageIds.Namespace); case Glyph.MethodPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPublic); case Glyph.MethodProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodProtected); case Glyph.MethodPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPrivate); case Glyph.MethodInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodInternal); case Glyph.ModulePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePublic); case Glyph.ModuleProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleProtected); case Glyph.ModulePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePrivate); case Glyph.ModuleInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleInternal); case Glyph.OpenFolder: return new ImageId(ImageCatalogGuid, KnownImageIds.OpenFolder); case Glyph.Operator: return new ImageId(ImageCatalogGuid, KnownImageIds.Operator); case Glyph.PropertyPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPublic); case Glyph.PropertyProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyProtected); case Glyph.PropertyPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPrivate); case Glyph.PropertyInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyInternal); case Glyph.RangeVariable: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic); case Glyph.Reference: return new ImageId(ImageCatalogGuid, KnownImageIds.Reference); //// this is not a copy-paste mistake, we were using these before in the previous GetImageMoniker() //case Glyph.StructurePublic: // return KnownMonikers.ValueTypePublic; //case Glyph.StructureProtected: // return KnownMonikers.ValueTypeProtected; //case Glyph.StructurePrivate: // return KnownMonikers.ValueTypePrivate; //case Glyph.StructureInternal: // return KnownMonikers.ValueTypeInternal; case Glyph.StructurePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePublic); case Glyph.StructureProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeProtected); case Glyph.StructurePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePrivate); case Glyph.StructureInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeInternal); case Glyph.TypeParameter: return new ImageId(ImageCatalogGuid, KnownImageIds.Type); case Glyph.Snippet: return new ImageId(ImageCatalogGuid, KnownImageIds.Snippet); case Glyph.CompletionWarning: return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseWarning); case Glyph.StatusInformation: return new ImageId(ImageCatalogGuid, KnownImageIds.StatusInformation); case Glyph.NuGet: return new ImageId(ImageCatalogGuid, KnownImageIds.NuGet); case Glyph.TargetTypeMatch: return new ImageId(ImageCatalogGuid, KnownImageIds.MatchType); default: throw new ArgumentException(nameof(glyph)); } } public static ImageElement GetImageElement(this Glyph glyph) => new ImageElement(glyph.GetImageId()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class GlyphExtensions { // hardcode ImageCatalogGuid locally rather than calling KnownImageIds.ImageCatalogGuid // So it doesnot have dependency for Microsoft.VisualStudio.ImageCatalog.dll // https://github.com/dotnet/roslyn/issues/26642 private static readonly Guid ImageCatalogGuid = Guid.Parse("ae27a6b0-e345-4288-96df-5eaf394ee369"); public static ImageId GetImageCatalogImageId(int imageId) => new(ImageCatalogGuid, imageId); public static ImageId GetImageId(this Glyph glyph) { // VS for mac cannot refer to ImageMoniker // so we need to expose ImageId instead of ImageMoniker here // and expose ImageMoniker in the EditorFeatures.wpf.dll // The use of constants here is okay because the compiler inlines their values, so no runtime reference is needed. // There are tests in src\EditorFeatures\Test\AssemblyReferenceTests.cs to ensure we don't regress that. switch (glyph) { case Glyph.None: return default; case Glyph.Assembly: return new ImageId(ImageCatalogGuid, KnownImageIds.Assembly); case Glyph.BasicFile: return new ImageId(ImageCatalogGuid, KnownImageIds.VBFileNode); case Glyph.BasicProject: return new ImageId(ImageCatalogGuid, KnownImageIds.VBProjectNode); case Glyph.ClassPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPublic); case Glyph.ClassProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassProtected); case Glyph.ClassPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPrivate); case Glyph.ClassInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ClassInternal); case Glyph.CSharpFile: return new ImageId(ImageCatalogGuid, KnownImageIds.CSFileNode); case Glyph.CSharpProject: return new ImageId(ImageCatalogGuid, KnownImageIds.CSProjectNode); case Glyph.ConstantPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPublic); case Glyph.ConstantProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantProtected); case Glyph.ConstantPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPrivate); case Glyph.ConstantInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantInternal); case Glyph.DelegatePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePublic); case Glyph.DelegateProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateProtected); case Glyph.DelegatePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePrivate); case Glyph.DelegateInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateInternal); case Glyph.EnumPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPublic); case Glyph.EnumProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationProtected); case Glyph.EnumPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPrivate); case Glyph.EnumInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationInternal); case Glyph.EnumMemberPublic: case Glyph.EnumMemberProtected: case Glyph.EnumMemberPrivate: case Glyph.EnumMemberInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationItemPublic); case Glyph.Error: return new ImageId(ImageCatalogGuid, KnownImageIds.StatusError); case Glyph.EventPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.EventPublic); case Glyph.EventProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.EventProtected); case Glyph.EventPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.EventPrivate); case Glyph.EventInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.EventInternal); // Extension methods have the same glyph regardless of accessibility. case Glyph.ExtensionMethodPublic: case Glyph.ExtensionMethodProtected: case Glyph.ExtensionMethodPrivate: case Glyph.ExtensionMethodInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ExtensionMethod); case Glyph.FieldPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic); case Glyph.FieldProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldProtected); case Glyph.FieldPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPrivate); case Glyph.FieldInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldInternal); case Glyph.InterfacePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePublic); case Glyph.InterfaceProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceProtected); case Glyph.InterfacePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePrivate); case Glyph.InterfaceInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceInternal); // TODO: Figure out the right thing to return here. case Glyph.Intrinsic: return new ImageId(ImageCatalogGuid, KnownImageIds.Type); case Glyph.Keyword: return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseKeyword); case Glyph.Label: return new ImageId(ImageCatalogGuid, KnownImageIds.Label); case Glyph.Parameter: case Glyph.Local: return new ImageId(ImageCatalogGuid, KnownImageIds.LocalVariable); case Glyph.Namespace: return new ImageId(ImageCatalogGuid, KnownImageIds.Namespace); case Glyph.MethodPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPublic); case Glyph.MethodProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodProtected); case Glyph.MethodPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPrivate); case Glyph.MethodInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.MethodInternal); case Glyph.ModulePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePublic); case Glyph.ModuleProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleProtected); case Glyph.ModulePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePrivate); case Glyph.ModuleInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleInternal); case Glyph.OpenFolder: return new ImageId(ImageCatalogGuid, KnownImageIds.OpenFolder); case Glyph.Operator: return new ImageId(ImageCatalogGuid, KnownImageIds.Operator); case Glyph.PropertyPublic: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPublic); case Glyph.PropertyProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyProtected); case Glyph.PropertyPrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPrivate); case Glyph.PropertyInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyInternal); case Glyph.RangeVariable: return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic); case Glyph.Reference: return new ImageId(ImageCatalogGuid, KnownImageIds.Reference); //// this is not a copy-paste mistake, we were using these before in the previous GetImageMoniker() //case Glyph.StructurePublic: // return KnownMonikers.ValueTypePublic; //case Glyph.StructureProtected: // return KnownMonikers.ValueTypeProtected; //case Glyph.StructurePrivate: // return KnownMonikers.ValueTypePrivate; //case Glyph.StructureInternal: // return KnownMonikers.ValueTypeInternal; case Glyph.StructurePublic: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePublic); case Glyph.StructureProtected: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeProtected); case Glyph.StructurePrivate: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePrivate); case Glyph.StructureInternal: return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeInternal); case Glyph.TypeParameter: return new ImageId(ImageCatalogGuid, KnownImageIds.Type); case Glyph.Snippet: return new ImageId(ImageCatalogGuid, KnownImageIds.Snippet); case Glyph.CompletionWarning: return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseWarning); case Glyph.StatusInformation: return new ImageId(ImageCatalogGuid, KnownImageIds.StatusInformation); case Glyph.NuGet: return new ImageId(ImageCatalogGuid, KnownImageIds.NuGet); case Glyph.TargetTypeMatch: return new ImageId(ImageCatalogGuid, KnownImageIds.MatchType); default: throw new ArgumentException(nameof(glyph)); } } public static ImageElement GetImageElement(this Glyph glyph) => new ImageElement(glyph.GetImageId()); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Remote/ServiceHub/Services/ServiceBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Roslyn.Utilities; #pragma warning disable CS0618 // Type or member is obsolete - this should become error once we provide infra for migrating to ISB (https://github.com/dotnet/roslyn/issues/44326) namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Base type with servicehub helper methods. this is not tied to how Roslyn OOP works. /// /// any type that derived from this type is supposed to be an entry point for servicehub services. /// name of the type should match one appears in GenerateServiceHubConfigurationFiles.targets /// and signature of either its constructor or static CreateAsync must follow the convension /// ctor(Stream stream, IServiceProvider serviceProvider). /// /// see servicehub detail from VSIDE onenote /// https://microsoft.sharepoint.com/teams/DD_VSIDE /// </summary> internal abstract class ServiceBase : IDisposable { private static int s_instanceId; protected readonly RemoteEndPoint EndPoint; protected readonly int InstanceId; protected readonly TraceSource Logger; protected readonly RemoteWorkspaceManager WorkspaceManager; // test data are only available when running tests: internal readonly RemoteHostTestData? TestData; static ServiceBase() { WatsonReporter.InitializeFatalErrorHandlers(); } protected ServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable<JsonConverter>? jsonConverters = null) { InstanceId = Interlocked.Add(ref s_instanceId, 1); TestData = (RemoteHostTestData?)serviceProvider.GetService(typeof(RemoteHostTestData)); WorkspaceManager = TestData?.WorkspaceManager ?? RemoteWorkspaceManager.Default; Logger = (TraceSource)serviceProvider.GetService(typeof(TraceSource)); Log(TraceEventType.Information, "Service instance created"); // invoke all calls incoming over the stream on this service instance: EndPoint = new RemoteEndPoint(stream, Logger, incomingCallTarget: this, jsonConverters); } public void Dispose() { if (EndPoint.IsDisposed) { // guard us from double disposing. this can happen in unit test // due to how we create test mock service hub stream that tied to // remote host service return; } EndPoint.Dispose(); Log(TraceEventType.Information, "Service instance disposed"); } protected void StartService() { EndPoint.StartListening(); } protected string DebugInstanceString => $"{GetType()} ({InstanceId})"; protected void Log(TraceEventType errorType, string message) => Logger.TraceEvent(errorType, 0, $"{DebugInstanceString}: {message}"); public RemoteWorkspace GetWorkspace() => WorkspaceManager.GetWorkspace(); protected Task<Solution> GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, WorkspaceManager.GetAssetSource()); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken).AsTask(); } internal Task<Solution> GetSolutionImplAsync(JObject solutionInfo, CancellationToken cancellationToken) { var reader = solutionInfo.CreateReader(); var serializer = JsonSerializer.Create(new JsonSerializerSettings() { Converters = new[] { AggregateJsonConverter.Instance }, DateParseHandling = DateParseHandling.None }); var pinnedSolutionInfo = serializer.Deserialize<PinnedSolutionInfo>(reader); return GetSolutionAsync(pinnedSolutionInfo, cancellationToken); } protected async Task<T> RunServiceAsync<T>(Func<Task<T>> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected async Task RunServiceAsync(Func<Task> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected T RunService<T>(Func<T> call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected void RunService(Action call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Roslyn.Utilities; #pragma warning disable CS0618 // Type or member is obsolete - this should become error once we provide infra for migrating to ISB (https://github.com/dotnet/roslyn/issues/44326) namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Base type with servicehub helper methods. this is not tied to how Roslyn OOP works. /// /// any type that derived from this type is supposed to be an entry point for servicehub services. /// name of the type should match one appears in GenerateServiceHubConfigurationFiles.targets /// and signature of either its constructor or static CreateAsync must follow the convension /// ctor(Stream stream, IServiceProvider serviceProvider). /// /// see servicehub detail from VSIDE onenote /// https://microsoft.sharepoint.com/teams/DD_VSIDE /// </summary> internal abstract class ServiceBase : IDisposable { private static int s_instanceId; protected readonly RemoteEndPoint EndPoint; protected readonly int InstanceId; protected readonly TraceSource Logger; protected readonly RemoteWorkspaceManager WorkspaceManager; // test data are only available when running tests: internal readonly RemoteHostTestData? TestData; static ServiceBase() { WatsonReporter.InitializeFatalErrorHandlers(); } protected ServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable<JsonConverter>? jsonConverters = null) { InstanceId = Interlocked.Add(ref s_instanceId, 1); TestData = (RemoteHostTestData?)serviceProvider.GetService(typeof(RemoteHostTestData)); WorkspaceManager = TestData?.WorkspaceManager ?? RemoteWorkspaceManager.Default; Logger = (TraceSource)serviceProvider.GetService(typeof(TraceSource)); Log(TraceEventType.Information, "Service instance created"); // invoke all calls incoming over the stream on this service instance: EndPoint = new RemoteEndPoint(stream, Logger, incomingCallTarget: this, jsonConverters); } public void Dispose() { if (EndPoint.IsDisposed) { // guard us from double disposing. this can happen in unit test // due to how we create test mock service hub stream that tied to // remote host service return; } EndPoint.Dispose(); Log(TraceEventType.Information, "Service instance disposed"); } protected void StartService() { EndPoint.StartListening(); } protected string DebugInstanceString => $"{GetType()} ({InstanceId})"; protected void Log(TraceEventType errorType, string message) => Logger.TraceEvent(errorType, 0, $"{DebugInstanceString}: {message}"); public RemoteWorkspace GetWorkspace() => WorkspaceManager.GetWorkspace(); protected Task<Solution> GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, WorkspaceManager.GetAssetSource()); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken).AsTask(); } internal Task<Solution> GetSolutionImplAsync(JObject solutionInfo, CancellationToken cancellationToken) { var reader = solutionInfo.CreateReader(); var serializer = JsonSerializer.Create(new JsonSerializerSettings() { Converters = new[] { AggregateJsonConverter.Instance }, DateParseHandling = DateParseHandling.None }); var pinnedSolutionInfo = serializer.Deserialize<PinnedSolutionInfo>(reader); return GetSolutionAsync(pinnedSolutionInfo, cancellationToken); } protected async Task<T> RunServiceAsync<T>(Func<Task<T>> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected async Task RunServiceAsync(Func<Task> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected T RunService<T>(Func<T> call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected void RunService(Action call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_GetDiagnostics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactory.PathSyntaxReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PathSyntaxReference : SyntaxReference { private readonly SyntaxTree _tree; private readonly SyntaxKind _kind; private readonly TextSpan _textSpan; private readonly ImmutableArray<int> _pathFromRoot; public PathSyntaxReference(SyntaxNode node) { _tree = node.SyntaxTree; _kind = node.Kind(); _textSpan = node.Span; _pathFromRoot = ComputePathFromRoot(node); } public override SyntaxTree SyntaxTree { get { return _tree; } } public override TextSpan Span { get { return _textSpan; } } private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node) { var path = new List<int>(); var root = _tree.GetRoot(); while (node != root) { for (; node.Parent != null; node = node.Parent) { var index = GetChildIndex(node); path.Add(index); } // if we were part of structure trivia, continue searching until we get to the true root if (node.IsStructuredTrivia) { var trivia = node.ParentTrivia; var triviaIndex = GetTriviaIndex(trivia); path.Add(triviaIndex); var tokenIndex = GetChildIndex(trivia.Token); path.Add(tokenIndex); node = trivia.Token.Parent; continue; } else if (node != root) { throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root); } } path.Reverse(); return path.ToImmutableArray(); } private static int GetChildIndex(SyntaxNodeOrToken child) { var parent = child.Parent; var index = 0; foreach (var nodeOrToken in parent.ChildNodesAndTokens()) { if (nodeOrToken == child) { return index; } index++; } throw new InvalidOperationException(CSharpWorkspaceResources.Node_not_in_parent_s_child_list); } private static int GetTriviaIndex(SyntaxTrivia trivia) { var token = trivia.Token; var index = 0; foreach (var tr in token.LeadingTrivia) { if (tr == trivia) { return index; } index++; } foreach (var tr in token.TrailingTrivia) { if (tr == trivia) { return index; } index++; } throw new InvalidOperationException(CSharpWorkspaceResources.Trivia_is_not_associated_with_token); } private static SyntaxTrivia GetTrivia(SyntaxToken token, int triviaIndex) { var leadingCount = token.LeadingTrivia.Count; if (triviaIndex <= leadingCount) { return token.LeadingTrivia.ElementAt(triviaIndex); } triviaIndex -= leadingCount; return token.TrailingTrivia.ElementAt(triviaIndex); } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) => this.GetNode(_tree.GetRoot(cancellationToken)); public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await _tree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var node = root; for (int i = 0, n = _pathFromRoot.Length; i < n; i++) { var child = node.ChildNodesAndTokens()[_pathFromRoot[i]]; if (child.IsToken) { // if child is a token then we must be looking for a node in structured trivia i++; System.Diagnostics.Debug.Assert(i < n); var triviaIndex = _pathFromRoot[i]; var trivia = GetTrivia(child.AsToken(), triviaIndex); node = trivia.GetStructure(); } else { node = child.AsNode(); } } System.Diagnostics.Debug.Assert(node.Kind() == _kind); System.Diagnostics.Debug.Assert(node.Span == _textSpan); return node; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PathSyntaxReference : SyntaxReference { private readonly SyntaxTree _tree; private readonly SyntaxKind _kind; private readonly TextSpan _textSpan; private readonly ImmutableArray<int> _pathFromRoot; public PathSyntaxReference(SyntaxNode node) { _tree = node.SyntaxTree; _kind = node.Kind(); _textSpan = node.Span; _pathFromRoot = ComputePathFromRoot(node); } public override SyntaxTree SyntaxTree { get { return _tree; } } public override TextSpan Span { get { return _textSpan; } } private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node) { var path = new List<int>(); var root = _tree.GetRoot(); while (node != root) { for (; node.Parent != null; node = node.Parent) { var index = GetChildIndex(node); path.Add(index); } // if we were part of structure trivia, continue searching until we get to the true root if (node.IsStructuredTrivia) { var trivia = node.ParentTrivia; var triviaIndex = GetTriviaIndex(trivia); path.Add(triviaIndex); var tokenIndex = GetChildIndex(trivia.Token); path.Add(tokenIndex); node = trivia.Token.Parent; continue; } else if (node != root) { throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root); } } path.Reverse(); return path.ToImmutableArray(); } private static int GetChildIndex(SyntaxNodeOrToken child) { var parent = child.Parent; var index = 0; foreach (var nodeOrToken in parent.ChildNodesAndTokens()) { if (nodeOrToken == child) { return index; } index++; } throw new InvalidOperationException(CSharpWorkspaceResources.Node_not_in_parent_s_child_list); } private static int GetTriviaIndex(SyntaxTrivia trivia) { var token = trivia.Token; var index = 0; foreach (var tr in token.LeadingTrivia) { if (tr == trivia) { return index; } index++; } foreach (var tr in token.TrailingTrivia) { if (tr == trivia) { return index; } index++; } throw new InvalidOperationException(CSharpWorkspaceResources.Trivia_is_not_associated_with_token); } private static SyntaxTrivia GetTrivia(SyntaxToken token, int triviaIndex) { var leadingCount = token.LeadingTrivia.Count; if (triviaIndex <= leadingCount) { return token.LeadingTrivia.ElementAt(triviaIndex); } triviaIndex -= leadingCount; return token.TrailingTrivia.ElementAt(triviaIndex); } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) => this.GetNode(_tree.GetRoot(cancellationToken)); public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await _tree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var node = root; for (int i = 0, n = _pathFromRoot.Length; i < n; i++) { var child = node.ChildNodesAndTokens()[_pathFromRoot[i]]; if (child.IsToken) { // if child is a token then we must be looking for a node in structured trivia i++; System.Diagnostics.Debug.Assert(i < n); var triviaIndex = _pathFromRoot[i]; var trivia = GetTrivia(child.AsToken(), triviaIndex); node = trivia.GetStructure(); } else { node = child.AsNode(); } } System.Diagnostics.Debug.Assert(node.Kind() == _kind); System.Diagnostics.Debug.Assert(node.Span == _textSpan); return node; } } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/CodeAnalysisTest/CommonParseOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonParseOptionsTests { /// <summary> /// If this test fails, please update the <see cref="ParseOptions.GetHashCodeHelper"/> /// and <see cref="ParseOptions.EqualsHelper"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(ParseOptions), "DocumentationMode", "Errors", "Features", "Kind", "Language", "PreprocessorSymbolNames", "SpecifiedKind"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonParseOptionsTests { /// <summary> /// If this test fails, please update the <see cref="ParseOptions.GetHashCodeHelper"/> /// and <see cref="ParseOptions.EqualsHelper"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(ParseOptions), "DocumentationMode", "Errors", "Features", "Kind", "Language", "PreprocessorSymbolNames", "SpecifiedKind"); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); nextHandler(); if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) { EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } // Event hookup is current uncancellable. var cancellationToken = CancellationToken.None; using (Logger.LogBlock(FunctionId.EventHookup_Type_Char, cancellationToken)) { if (args.TypedChar == '=') { // They've typed an equals. Cancel existing sessions and potentially start a // new session. EventHookupSessionManager.CancelAndDismissExistingSessions(); if (IsTextualPlusEquals(args.TextView, args.SubjectBuffer)) { EventHookupSessionManager.BeginSession(this, args.TextView, args.SubjectBuffer, _asyncListener, TESTSessionHookupMutex); } } else { // Spaces are the only non-'=' character that allow the session to continue if (args.TypedChar != ' ') { EventHookupSessionManager.CancelAndDismissExistingSessions(); } } } } private bool IsTextualPlusEquals(ITextView textView, ITextBuffer subjectBuffer) { AssertIsForeground(); var caretPoint = textView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var position = caretPoint.Value.Position; return position - 2 >= 0 && subjectBuffer.CurrentSnapshot.GetText(position - 2, 2) == "+="; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); return nextHandler(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); nextHandler(); if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) { EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } // Event hookup is current uncancellable. var cancellationToken = CancellationToken.None; using (Logger.LogBlock(FunctionId.EventHookup_Type_Char, cancellationToken)) { if (args.TypedChar == '=') { // They've typed an equals. Cancel existing sessions and potentially start a // new session. EventHookupSessionManager.CancelAndDismissExistingSessions(); if (IsTextualPlusEquals(args.TextView, args.SubjectBuffer)) { EventHookupSessionManager.BeginSession(this, args.TextView, args.SubjectBuffer, _asyncListener, TESTSessionHookupMutex); } } else { // Spaces are the only non-'=' character that allow the session to continue if (args.TypedChar != ' ') { EventHookupSessionManager.CancelAndDismissExistingSessions(); } } } } private bool IsTextualPlusEquals(ITextView textView, ITextBuffer subjectBuffer) { AssertIsForeground(); var caretPoint = textView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var position = caretPoint.Value.Position; return position - 2 >= 0 && subjectBuffer.CurrentSnapshot.GetText(position - 2, 2) == "+="; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); return nextHandler(); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Diagnostics/IFSharpUnusedDeclarationsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics { internal interface IFSharpUnusedDeclarationsDiagnosticAnalyzer { Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics { internal interface IFSharpUnusedDeclarationsDiagnosticAnalyzer { Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Symbols/ConstantValueUtils.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class EvaluatedConstant { public readonly ConstantValue Value; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public EvaluatedConstant(ConstantValue value, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.Value = value; this.Diagnostics = diagnostics.NullToEmpty(); } } internal static class ConstantValueUtils { public static ConstantValue EvaluateFieldConstant( SourceFieldSymbol symbol, EqualsValueClauseSyntax equalsValueNode, HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) { var compilation = symbol.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory((SyntaxTree)symbol.Locations[0].SourceTree); var binder = binderFactory.GetBinder(equalsValueNode); if (earlyDecodingWellKnownAttributes) { binder = new EarlyWellKnownAttributeBinder(binder); } var inProgressBinder = new ConstantFieldsInProgressBinder(new ConstantFieldsInProgress(symbol, dependencies), binder); BoundFieldEqualsValue boundValue = BindFieldOrEnumInitializer(inProgressBinder, symbol, equalsValueNode, diagnostics); var initValueNodeLocation = equalsValueNode.Value.Location; var value = GetAndValidateConstantValue(boundValue.Value, symbol, symbol.Type, initValueNodeLocation, diagnostics); Debug.Assert(value != null); return value; } private static BoundFieldEqualsValue BindFieldOrEnumInitializer( Binder binder, FieldSymbol fieldSymbol, EqualsValueClauseSyntax initializer, BindingDiagnosticBag diagnostics) { var enumConstant = fieldSymbol as SourceEnumConstantSymbol; Binder collisionDetector = new LocalScopeBinder(binder); collisionDetector = new ExecutableCodeBinder(initializer, fieldSymbol, collisionDetector); BoundFieldEqualsValue result; if ((object)enumConstant != null) { result = collisionDetector.BindEnumConstantInitializer(enumConstant, initializer, diagnostics); } else { result = collisionDetector.BindFieldInitializer(fieldSymbol, initializer, diagnostics); } return result; } internal static string UnescapeInterpolatedStringLiteral(string s) { var builder = PooledStringBuilder.GetInstance(); var stringBuilder = builder.Builder; int formatLength = s.Length; for (int i = 0; i < formatLength; i++) { char c = s[i]; stringBuilder.Append(c); if ((c == '{' || c == '}') && (i + 1) < formatLength && s[i + 1] == c) { i++; } } return builder.ToStringAndFree(); } internal static ConstantValue GetAndValidateConstantValue( BoundExpression boundValue, Symbol thisSymbol, TypeSymbol typeSymbol, Location initValueNodeLocation, BindingDiagnosticBag diagnostics) { var value = ConstantValue.Bad; CheckLangVersionForConstantValue(boundValue, diagnostics); if (!boundValue.HasAnyErrors) { if (typeSymbol.TypeKind == TypeKind.TypeParameter) { diagnostics.Add(ErrorCode.ERR_InvalidConstantDeclarationType, initValueNodeLocation, thisSymbol, typeSymbol); } else { bool hasDynamicConversion = false; var unconvertedBoundValue = boundValue; while (unconvertedBoundValue.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)unconvertedBoundValue; hasDynamicConversion = hasDynamicConversion || conversion.ConversionKind.IsDynamic(); unconvertedBoundValue = conversion.Operand; } // If we have already computed the unconverted constant value, then this call is cheap // because BoundConversions store their constant values (i.e. not recomputing anything). var constantValue = boundValue.ConstantValue; var unconvertedConstantValue = unconvertedBoundValue.ConstantValue; if (unconvertedConstantValue != null && !unconvertedConstantValue.IsNull && typeSymbol.IsReferenceType && typeSymbol.SpecialType != SpecialType.System_String) { // Suppose we are in this case: // // const object x = "some_string" // // A constant of type object can only be initialized to // null; it may not contain an implicit reference conversion // from string. // // Give a special error for that case. diagnostics.Add(ErrorCode.ERR_NotNullConstRefField, initValueNodeLocation, thisSymbol, typeSymbol); // If we get here, then the constantValue will likely be null. // However, it seems reasonable to assume that the programmer will correct the error not // by changing the value to "null", but by updating the type of the constant. Consequently, // we retain the unconverted constant value so that it can propagate through the rest of // constant folding. constantValue = constantValue ?? unconvertedConstantValue; } if (constantValue != null && !hasDynamicConversion) { value = constantValue; } else { diagnostics.Add(ErrorCode.ERR_NotConstantExpression, initValueNodeLocation, thisSymbol); } } } return value; } private sealed class CheckConstantInterpolatedStringValidity : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { internal readonly BindingDiagnosticBag diagnostics; public CheckConstantInterpolatedStringValidity(BindingDiagnosticBag diagnostics) { this.diagnostics = diagnostics; } public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { Binder.CheckFeatureAvailability(node.Syntax, MessageID.IDS_FeatureConstantInterpolatedStrings, diagnostics); return null; } } internal static void CheckLangVersionForConstantValue(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (!(expression.Type is null) && expression.Type.IsStringType()) { var visitor = new CheckConstantInterpolatedStringValidity(diagnostics); visitor.Visit(expression); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class EvaluatedConstant { public readonly ConstantValue Value; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public EvaluatedConstant(ConstantValue value, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.Value = value; this.Diagnostics = diagnostics.NullToEmpty(); } } internal static class ConstantValueUtils { public static ConstantValue EvaluateFieldConstant( SourceFieldSymbol symbol, EqualsValueClauseSyntax equalsValueNode, HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) { var compilation = symbol.DeclaringCompilation; var binderFactory = compilation.GetBinderFactory((SyntaxTree)symbol.Locations[0].SourceTree); var binder = binderFactory.GetBinder(equalsValueNode); if (earlyDecodingWellKnownAttributes) { binder = new EarlyWellKnownAttributeBinder(binder); } var inProgressBinder = new ConstantFieldsInProgressBinder(new ConstantFieldsInProgress(symbol, dependencies), binder); BoundFieldEqualsValue boundValue = BindFieldOrEnumInitializer(inProgressBinder, symbol, equalsValueNode, diagnostics); var initValueNodeLocation = equalsValueNode.Value.Location; var value = GetAndValidateConstantValue(boundValue.Value, symbol, symbol.Type, initValueNodeLocation, diagnostics); Debug.Assert(value != null); return value; } private static BoundFieldEqualsValue BindFieldOrEnumInitializer( Binder binder, FieldSymbol fieldSymbol, EqualsValueClauseSyntax initializer, BindingDiagnosticBag diagnostics) { var enumConstant = fieldSymbol as SourceEnumConstantSymbol; Binder collisionDetector = new LocalScopeBinder(binder); collisionDetector = new ExecutableCodeBinder(initializer, fieldSymbol, collisionDetector); BoundFieldEqualsValue result; if ((object)enumConstant != null) { result = collisionDetector.BindEnumConstantInitializer(enumConstant, initializer, diagnostics); } else { result = collisionDetector.BindFieldInitializer(fieldSymbol, initializer, diagnostics); } return result; } internal static string UnescapeInterpolatedStringLiteral(string s) { var builder = PooledStringBuilder.GetInstance(); var stringBuilder = builder.Builder; int formatLength = s.Length; for (int i = 0; i < formatLength; i++) { char c = s[i]; stringBuilder.Append(c); if ((c == '{' || c == '}') && (i + 1) < formatLength && s[i + 1] == c) { i++; } } return builder.ToStringAndFree(); } internal static ConstantValue GetAndValidateConstantValue( BoundExpression boundValue, Symbol thisSymbol, TypeSymbol typeSymbol, Location initValueNodeLocation, BindingDiagnosticBag diagnostics) { var value = ConstantValue.Bad; CheckLangVersionForConstantValue(boundValue, diagnostics); if (!boundValue.HasAnyErrors) { if (typeSymbol.TypeKind == TypeKind.TypeParameter) { diagnostics.Add(ErrorCode.ERR_InvalidConstantDeclarationType, initValueNodeLocation, thisSymbol, typeSymbol); } else { bool hasDynamicConversion = false; var unconvertedBoundValue = boundValue; while (unconvertedBoundValue.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)unconvertedBoundValue; hasDynamicConversion = hasDynamicConversion || conversion.ConversionKind.IsDynamic(); unconvertedBoundValue = conversion.Operand; } // If we have already computed the unconverted constant value, then this call is cheap // because BoundConversions store their constant values (i.e. not recomputing anything). var constantValue = boundValue.ConstantValue; var unconvertedConstantValue = unconvertedBoundValue.ConstantValue; if (unconvertedConstantValue != null && !unconvertedConstantValue.IsNull && typeSymbol.IsReferenceType && typeSymbol.SpecialType != SpecialType.System_String) { // Suppose we are in this case: // // const object x = "some_string" // // A constant of type object can only be initialized to // null; it may not contain an implicit reference conversion // from string. // // Give a special error for that case. diagnostics.Add(ErrorCode.ERR_NotNullConstRefField, initValueNodeLocation, thisSymbol, typeSymbol); // If we get here, then the constantValue will likely be null. // However, it seems reasonable to assume that the programmer will correct the error not // by changing the value to "null", but by updating the type of the constant. Consequently, // we retain the unconverted constant value so that it can propagate through the rest of // constant folding. constantValue = constantValue ?? unconvertedConstantValue; } if (constantValue != null && !hasDynamicConversion) { value = constantValue; } else { diagnostics.Add(ErrorCode.ERR_NotConstantExpression, initValueNodeLocation, thisSymbol); } } } return value; } private sealed class CheckConstantInterpolatedStringValidity : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { internal readonly BindingDiagnosticBag diagnostics; public CheckConstantInterpolatedStringValidity(BindingDiagnosticBag diagnostics) { this.diagnostics = diagnostics; } public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { Binder.CheckFeatureAvailability(node.Syntax, MessageID.IDS_FeatureConstantInterpolatedStrings, diagnostics); return null; } } internal static void CheckLangVersionForConstantValue(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (!(expression.Type is null) && expression.Type.IsStringType()) { var visitor = new CheckConstantInterpolatedStringValidity(diagnostics); visitor.Visit(expression); } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationAbstractNamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class CodeGenerationAbstractNamedTypeSymbol : CodeGenerationTypeSymbol, INamedTypeSymbol { public new INamedTypeSymbol OriginalDefinition { get; protected set; } public ImmutableArray<IFieldSymbol> TupleElements { get; protected set; } internal readonly ImmutableArray<CodeGenerationAbstractNamedTypeSymbol> TypeMembers; protected CodeGenerationAbstractNamedTypeSymbol( IAssemblySymbol containingAssembly, INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, string name, SpecialType specialType, NullableAnnotation nullableAnnotation, ImmutableArray<CodeGenerationAbstractNamedTypeSymbol> typeMembers) : base(containingAssembly, containingType, attributes, declaredAccessibility, modifiers, name, specialType, nullableAnnotation) { this.TypeMembers = typeMembers; foreach (var member in typeMembers) { member.ContainingType = this; } } public override SymbolKind Kind => SymbolKind.NamedType; public override void Accept(SymbolVisitor visitor) => visitor.VisitNamedType(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitNamedType(this); public INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments) { if (typeArguments.Length == 0) { return this; } return new CodeGenerationConstructedNamedTypeSymbol( ConstructedFrom, typeArguments.ToImmutableArray(), this.TypeMembers); } public INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) { return new CodeGenerationConstructedNamedTypeSymbol( ConstructedFrom, typeArguments, this.TypeMembers); } public abstract int Arity { get; } public abstract bool IsGenericType { get; } public abstract bool IsUnboundGenericType { get; } public abstract bool IsScriptClass { get; } public abstract bool IsImplicitClass { get; } public abstract IEnumerable<string> MemberNames { get; } public abstract IMethodSymbol DelegateInvokeMethod { get; } public abstract INamedTypeSymbol EnumUnderlyingType { get; } protected abstract CodeGenerationNamedTypeSymbol ConstructedFrom { get; } INamedTypeSymbol INamedTypeSymbol.ConstructedFrom => this.ConstructedFrom; public abstract INamedTypeSymbol ConstructUnboundGenericType(); public abstract ImmutableArray<IMethodSymbol> InstanceConstructors { get; } public abstract ImmutableArray<IMethodSymbol> StaticConstructors { get; } public abstract ImmutableArray<IMethodSymbol> Constructors { get; } public abstract ImmutableArray<ITypeSymbol> TypeArguments { get; } public abstract ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } public ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal) { if (ordinal < 0 || ordinal >= Arity) { throw new IndexOutOfRangeException(); } return ImmutableArray.Create<CustomModifier>(); } public abstract ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } public override string MetadataName { get { return this.Arity > 0 ? this.Name + "`" + Arity : base.MetadataName; } } public ISymbol AssociatedSymbol { get; internal set; } public bool MightContainExtensionMethods => false; public bool IsComImport => false; public bool IsUnmanagedType => throw new NotImplementedException(); public bool IsRefLikeType => Modifiers.IsRef; public INamedTypeSymbol NativeIntegerUnderlyingType => null; public INamedTypeSymbol TupleUnderlyingType => null; public bool IsSerializable => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class CodeGenerationAbstractNamedTypeSymbol : CodeGenerationTypeSymbol, INamedTypeSymbol { public new INamedTypeSymbol OriginalDefinition { get; protected set; } public ImmutableArray<IFieldSymbol> TupleElements { get; protected set; } internal readonly ImmutableArray<CodeGenerationAbstractNamedTypeSymbol> TypeMembers; protected CodeGenerationAbstractNamedTypeSymbol( IAssemblySymbol containingAssembly, INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, string name, SpecialType specialType, NullableAnnotation nullableAnnotation, ImmutableArray<CodeGenerationAbstractNamedTypeSymbol> typeMembers) : base(containingAssembly, containingType, attributes, declaredAccessibility, modifiers, name, specialType, nullableAnnotation) { this.TypeMembers = typeMembers; foreach (var member in typeMembers) { member.ContainingType = this; } } public override SymbolKind Kind => SymbolKind.NamedType; public override void Accept(SymbolVisitor visitor) => visitor.VisitNamedType(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitNamedType(this); public INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments) { if (typeArguments.Length == 0) { return this; } return new CodeGenerationConstructedNamedTypeSymbol( ConstructedFrom, typeArguments.ToImmutableArray(), this.TypeMembers); } public INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) { return new CodeGenerationConstructedNamedTypeSymbol( ConstructedFrom, typeArguments, this.TypeMembers); } public abstract int Arity { get; } public abstract bool IsGenericType { get; } public abstract bool IsUnboundGenericType { get; } public abstract bool IsScriptClass { get; } public abstract bool IsImplicitClass { get; } public abstract IEnumerable<string> MemberNames { get; } public abstract IMethodSymbol DelegateInvokeMethod { get; } public abstract INamedTypeSymbol EnumUnderlyingType { get; } protected abstract CodeGenerationNamedTypeSymbol ConstructedFrom { get; } INamedTypeSymbol INamedTypeSymbol.ConstructedFrom => this.ConstructedFrom; public abstract INamedTypeSymbol ConstructUnboundGenericType(); public abstract ImmutableArray<IMethodSymbol> InstanceConstructors { get; } public abstract ImmutableArray<IMethodSymbol> StaticConstructors { get; } public abstract ImmutableArray<IMethodSymbol> Constructors { get; } public abstract ImmutableArray<ITypeSymbol> TypeArguments { get; } public abstract ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } public ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal) { if (ordinal < 0 || ordinal >= Arity) { throw new IndexOutOfRangeException(); } return ImmutableArray.Create<CustomModifier>(); } public abstract ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } public override string MetadataName { get { return this.Arity > 0 ? this.Name + "`" + Arity : base.MetadataName; } } public ISymbol AssociatedSymbol { get; internal set; } public bool MightContainExtensionMethods => false; public bool IsComImport => false; public bool IsUnmanagedType => throw new NotImplementedException(); public bool IsRefLikeType => Modifiers.IsRef; public INamedTypeSymbol NativeIntegerUnderlyingType => null; public INamedTypeSymbol TupleUnderlyingType => null; public bool IsSerializable => false; } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./docs/wiki/documents/csharp-syntax.docx
PK!~ [Content_Types].xml (Ė]K0Cɭ " ?.UP@֜LݿdȶBsR[W'y:f Je{{]$0RT@ƖdtRpu`h^ W?Nbb<5G=trXT<|rM̜%wu]ʘQF** }iQÔrUJlI;3WIh_K.mФLwlErhyCtKJ-Yo0 =OÃ֝ԾH!N/F˼!n#bX;w" $=//kk3>#ϟĬ!N_fW$Ux $m燨Q<6h"AnlPK!N _rels/.rels (j0 @ѽQN/c[ILj<]aGӓzsFu]U ^[x1xp f#I)ʃY*D i")c$qU~31jH[{=E~ f?3-޲]Tꓸ2j),l0/%b zʼn, /|f\Z?6!Y_o]APK!4zeHword/_rels/document.xml.rels (N0EHC=qByi7[(ƓǑ{FںZ,s掝[u'j,Xf,,l.% ۀe:m&m'mـ6= }QQijދCGY6f'=,YH_nzOo]Um Ϻ\+@wƂ7 $(L zn<F1*!h`c"?+؉yc}1!uupcZPGĄHMau(pRp Q)܉1> mL/Xy=18<$*n)ViOOPK!ɉ-F#>tword/document.xml}nH wz 8"3$X,.hxLZX pu$']MfCd7E>o΋? _HhׯN~p^N$uùDKN?ܟͣ S &g٫E.^Lf MNoY%Uz:n_FWW{y(eͼ$AYnx&'tѢWQ|߬/K7/Oآ :Y xDވy%L)/c/@0Daet =\dܱqwd߻_Jj==g3 sm@ g(;C8gɭ뇛;&\Ik7\`yos^j7ڛf=pv&痖]"ؽ DhuIh.ҍ7W'H=>FMM}zQ4F돦ޕ RxO後'|>sN>.S? xN .ADCm/"}~_,<}!XH D2}Q<_?;x+%kO4]3Mts, rHMQRO0R4Qr=R.*0BVKS‡ԍSo^XCm$$=?+ w,e%^|睜 QEU5!Lݏ8tOx09-N9jHvd*`tdcլ¨訒3-`~-eƳkѹpر*Vd{h]ŠA+bEB*`|T<t+b/?xPd]̒\b:ZhRdE';u.puKDp$~f}ht-$OVnm5#dfk9.aBuP5bLכDGp.l;߻@ ["RdijNM> E2ũ^I')X@ʇ#|DR»]cqtMmMedF)0#lENGUL_?@tp7/9Bȡ%*iL'd-`cy4La&LhR:.,,|d|f[tĝtfʾIE"YS"ݔ>]E4wJk-?g}s,ʄ E'e )R #0NMv}Oe4ioC]7eH>zr\j1^.<!Z1mSWԍ PB#!}#,ETla~&FFm />r& Av?!Tf B #OErjj4*.KTgث~A {Dl AU4KCIi#֖c8 LĴϻh emKD=G)= :ЄB,\u#Mr,(j|x@`~V! e#kW,Mϼsm?$8L>BlA~K%i/+ŰUkdwo袪(We[s綮G*lj4Ao/h;F0a,Mq6 /oΒ4ğT"[ whvZ ²?,9ve#~breW Mhmܤ8Z]/{ FKO=SRX7M 8}(S3 R2z?yIȼiЮΈ/cԬ>ܻJNG0#bDQ^<iMC"3c^A2Ox$5)l̛a+#)Hzjb ˶e-l&3Wkٰ-(hbɺ^)lS@ܲj{d8Mv57u8'Pstb<sf$*'LAI@u&YTY8 %vx`PImDW!:2mDŽ˕)0@acNt~%S[w ^U .MLt8@+sCp`g492"^!"M=<'2Q&?+, *^'B`:~^{XamAD H̓0cH;a6@ȤA@f$,2Cqj7z uޮR7}),~ ̐VH@IDaX.LVprQXn*/DlHd"G.aeU橙dnW- `!UŀddO&B{^ZJAQj2b~f6裏84 O[(Do\E)9 '*pIwIz%q mGOLwlao`:`ߦUaެ ,,M%ݜ2BnŽl< (H#BFF B/}PHZT8 ΅N˒n4lDeƠX%azL~,l!$;!y`EMΌ>I*pC:+f~ $^3IḘ7և/o<A,;B:-%Crk'"˴<80, kf- ~"lfHlw*0ҟz~xA(!^#L5r='< 7$)7x` p/G4(%H8c{sΟO{XPmL nE7st,W!Z2]w9Z'HۄؓjIM)9Oˏ@50F>x6_*~l=/S~n@O_2Hd_k`$6`c."<`pOGd%3BJ"9RgXKeoMфU68!39qBmM(IU>angenHkqbr%H_ 1< S;\/nddhEw2/ ~yb+$p~` `[w~>'.M&.xgGG9zhl2 k&\ :֋N>T%z_q1pgoFVCh1N-<{fF#{O{ſ\ ?cHt{?% } E7b e*IRYQ' D7)>YO} hLjfa@ Ҹ] f붴ɄP|RPa[|D&T(u#!)/Z; g$X5Bt2^cpQJgkDaO'N`:ܙXR{"9S0H*,>t)jtMtF]bWilhC@Qѻ8 B8mOO?Np"q )4{Y%? f ݐ bvo]]!M&K=nNK8ʾ<fbG䙼n.+ۻ`3'F_g[>dC;# J<Κj wdx;ͻy% t\~=Zx Tw =/Ҷ޻ % ? w{qa=CF#%h`<f(-{*+#& 1,}y}'k/o{cBɾB!7rRk- 2PyS!uω'JIC-ZfÄQ T?cQ& #ÛQ"vz7k|?vy"/A?̎Yu_1'Q~<`u EZ$%/a,o$eqyZѿh jhxd4򇙪 8xFix5d DXRkR:3󚌃L[R.~d62x^D)A1#i P6T @ F6Ln*MvHTcXxKR݆CeEM7Oҿpd]KZ !Nz6dx-4L3=..ؠ_;Obî| 6g,Iм繛K7_T`ܜO;kv%-yd; UMQW+QԋTq5c+5P( %Q3YUL {6Xp܀u18L,3ʴ3VZeZ|Rs ~Lֺ)1JRoklΔ9*iO%#dkE56ID"YR3⃲ ܻűw؛\I`{z~qxU)c ,1y8ǑSȈLX+@CMpeIKUEtS3&S T_"'mEvM;p}"4h#.+0קHhNK~\MSuHO+GwQK%qzM/R qor $q$m"[[##:j/D/Z;DCo F -%2pIv|'+44 AbI%-QөRaiiޯQA_?mp&vWTgbݪ"c2B~'tpT֕JnkNnZ&rLɷJ3}~lz$/[x.8kh߰)a~ܶ ][<"*fHT6UniqYJWiX7\"BW U~(7H:Ox]int@[s(u݄q|W_> ÚҪquuT-|8n=K z݄,I0~C eM ':ъtN~!{Vt;ɘج X#+&‘M$n?"atZHXV4uPv8z88ۺ2)~⠶dkk爡FӃ_>#UhDۑx1f]Ͽ|/Ƴ$љ|Im#JkPz$¶P鯱zHwG-z~'ƎjOEU&Hq|wnmMӗq7cg-^ ~J.A)+:iL7pw nKZkeudDם]ᢪLb)AU hP7p4Zއ ±\ƀ9.śv)#!/\,#?ĵl%]֦n%btԟVR =(w>5GcK!Ӎ)56 e#띿_hNZUd;.屮 Ɇ`ß\#q,QBr0Z!, Ai>d@fs" ,7BZ6d*Ѧ Iw$>6JiEZηVusDXzqs7%uq]/ "'l!J GQX9a3cNpW>Tly4=Mg;=.~ugZq~u`䩲Ʃߥ@W$*ɜxӒW WVhH,WET[ɜd*`R1@bT6 J5KDY}\̕ Q*tܡ,\O=sd̒9.`ai%seFl`e64릆s[A4]G|*PB  kF*:k04F]dzi.Ƒ$q:scUy*.SR(~Իianyқփ9c$F+R$MEsZՏj'~@".'tIX7"6lꏕ͐UV8c`b_⡄>zXn;y*ie?Q?G5CI$|KJsU:V8|ȀgS4֜Q9RzRRؔ)9:MHyK;x(25YNnդ9n[QTUeVOɣ}CboaV{޸?2I#yt ]ϵqn f/7n[R,G؛b*`656)9=5:kk0o'~׼wP(wOI<)ZRn0lSn[  &a]tGn آ-UvޙSSŲQWԿE<,qپ\<7JR5,Ύ<"r`%,o2 j7?%5R KHGh"E%bar8.`4jbNNQt{'41+]w9Eyt+,Ś%[#?Z*8mX´14ߏ* svp =ְ)a4E>uj'}+j膴wί`z-XP}>Ξ!p\w9y!g#_͍2_{r@ 1,r,8[rB߲P?-sqfl1mm*a2*.8,@KVLSmJ>«>Ԗ`|ڪ#Р4硡őDW܂uKģh. B'`w  v|LJ}I,/ 핊7kqK{7nMuYdm/qN ])ENGkqф& 8ٳq]_[-ErI&y7:U]DH;CRʼnXRFВ4{IΩ5rR6zԫ;4-;fГ`cen͆ B;'ɸ Z;0QUz 6,U w9%|.q΄ٵ Ŗ)YG,2#A:gSح5㦔<ISb:CɂDžߊ_@KޮG]Ge{#*VU%fJ<V>he!-བྷafk3gfxֿy`K!K)n8->2S}i O& gEvo\QL۴!?,Nnh,xq ?,K107$aP7JA8[<d}|;/ $k=CuNl>4 %86;/ix'j8?ޜUF/AS,͸:tPT&39? 1 /P*ᴁj""(̍+0ԶĢu-XI=/#l_70!\*CCNVf)]iAGT ǚ":&WAmj`>F VL%0,F[f)hlTڊxɟӅ'j,[aKf5/yu_+If %mx[r|buٸ⺑̮Iz<a3<u37z<W WMtwmKa,zcyH<UeǭFˌnᖌؚNDL'ӑM5" g5yTVEÖmJND'K FH* Ad)]8pECtGG Az*zG;l,cW?fKQǞŬa۵hħЋAyu;Mc=`DR91 $,酛0oYD~4e b4[TFc~gqDWF58҆qߐK5 +SKpN(dwS;_ S 0Q4.bRg0+14ͼ"nͭ؄-F!y/傝?Ktv{lwvv7m:MKh|h]6 r??hZ*/ B~m @yw0Oi,TUs,VC@ڑߟNhe{Rou {a5Zᵔݓ m/wekOw?NLj$}w7)cc: _c?y=;9X仧x~ɮA!ANw@~d]}?ç5@cEv].50ЋwR\ucˆcQՍrzi^{[^gOfVS;v;ArX:%Xz}(xs3cD谋! o)XvNMǚۭis#oc%i`FsCPٓl)pR^\i6`g zك߼)nF/fY^,˪u˨,>ʨ$dI,Xy@ˢ&Z]CL{cXkNbdlT -v% tMЭ.VeXb6*>:b΃zoA0+14֘%CNo4oR2Jg% 9l-6ͽ+?Krbe#6$CՆW>S*C3/lee'wS/x[?X |t skRqZؼl]D:џ(ULc9Ta|?`I]X!=NHٴ hNt,w!GX \?/7aA #Օ*^_ eKTuK**h/ ,ρ=zYWȘU,Ov_C8oUMx2?xa=_WFmQbm">H&IឦCE*jDvTH#b.yKiGqf (w^2Z Eҿ 8yP#*%#҇(n-`^%RuEIek9@1xVDЎ@] A讫&Yd[BʿX%e`7 Wȑ"KԄks oXI-zV#!PLi) }aNJ"92k``SR`Śj^;?ZI29hHejKhbKxODGOsKF:F|ڷVSS \} 1oؑ>hдM[ώ}q B;lPgnc( Q+?5!wLv?_AW {`Pt/,my/"?C^<x~nn1+-z 9:Ķ|[ۺxSlgO;n4Xe{ bC!1 򓷜3,tm~x %K۳sR[h y85E~9r+,n$KpgզW#̉mɥ +"y?CGN؛,F=FT6d,ȩ>'&oHHFG1 5QB[ic,ZʎeڪSllKة!N4"AunNil0kyTdKفѣ1Ls0z#(5k}J84Ps=!b]iv9t\l-TCxJM}|H o н]^Ljm2Y+GM:`D]C.XT: b^C 'd(-p5]5'FQWEDȗgv)`!_ n*<s&VMlVK+(*ECZ5ڞ*EO0ytp{7LA0Bp9`Bx"WH̿.8d9F.bfYriְcIhm֕'hX"RmC]<DM Iwp'] u1W6bn" >m hn;J8XCos$d /JƄhU%ƗT0u[:e3`zrB'*nB:@?mIkd?C[ -)1IeW$ 8gP ˠ3zwX% a=1[P1l!lylݑg9&u&hc@ ]] x{RKqe[-M,}"tHգh# BAbTWp9sݶD#6h%]@W B}"@6@T0%'0EMj~Tgqgx}LӬuqı6Fklr"<&+HU?Ŷ]%j0FlړPG1U=}sI6hllVkK&EQβEjI\`KÍ~'܇fvb\H!lHO3}@kn 2gJ@VD[ T}45EDZF֕mЇ>%gjkcD#ӇM~h w/ 'Hh3@Ghd%gei |{;? +4ӽ訏/W%Ab'3Mq⻯N.|$'Gn M Vb^s8pw k45 ꍽgul0g(lsJiK9w. vI‘] ܵFo96;}^ώ(lN ~8@o85[sAF)Y v[=^:}jv  HȃXO#[+\ԋhwƔqFqֺoC;*-1nQOƥ #81wüǧ"rG<R~hSTGH3/9JopiW{'7ԑYZ8,GLu:kq6wu]јsA}x߸2q㣒DC[~˂JHddvZm7G*L;}g-ۥ@_B?VwG|c>n{H{DkEwO:u[c C7GdSnK:4|?hh aæ.[s0لd) . TЇaJz@4Eϳ/i$lRH}$/$EaSM$"#א,$ۊaM4rHOHpW'EzBnN4 7#ebRbpIU'Ĺta\פnul78;mi\CլܖJ)Z{/U%qK NϷ +I"Xr kR؈5Ci?nNJgVURnR U 5qBGdeȒV*InƩ5غ!雊r9.7ro$ݣs-j, Y&`Eέ`|F " ӑ,)h$<i:2F!lXS2T%e(ȒxG[Y٠n&j^]ð @<A`?HHVVTr%ٮ3y@V(ϋ{CFt;s[d@AMVlt%.@ͥYY26I}Ԛ?n-(^LUW$;:!9*Rs ATkÈ!mu.M\C>&M׭`翙hS"¶u_V<l]9z1eLmS)Z!O"nru3!( yk0$*:{:׾=\pآ΍}8h4&9 4 T+O,hI{\Պ(nrq.0Kz7Nxh`_rL==s~3'aVes$oڴsJ7xlR'%LZ O},Md$ *nc:imR;9y*8:O U4s[W1 ]a΀h)0j2$ :%M0ɅE>ӓEWȰxή͡cĀ:5Q}]!]ŖAUZ5Ќ˱ݜ4l&;qUU_̅x:gKah]j=Ǐ#F!;^@31.Х1xtThFu i+C/"V׋] '@dtEiDu<'R J_գE[pBpcOcJp~Lgt^j)S&cSuջ[#-A<ͱ=Gظ0b UF?!u$X4=LGøwqo. ,~iD-aG^B:#Vwi Fv!3 H~gs/yڳnrZH=E֍ == _i9@k"c/i<xس:DȒaofN򻾗 '[GwY G. zcqaABzawiԍW4NZswûXٺNNalaw用B3_ _N W~Z/) “5.ZG8L"Zs! nǁ~崔k86+d(zY)WN_rx c64:51ҩ5M{` ^L'ZLω7X@ MnAl2 $PL; pNDSp֘:Lm 63 ohB{#v6iGJQBC 2`ƚ }q)r0.dQ7VsAF{.qg1un X̊[anD['&9f=؋9f jh*gHaumj<ip9# v QGddMѵFWS㠪m]㠓5o409GNh9 u p+ٟ=yiՇ9}Σ/Y!4_m}M"V"G25C*4Z]bæ,-C kdW<ɖ6m[rrU|rp?SD.GI,u0r2ud)9'V, z -?LR7 >"yisn`BC2('Zte͖R/怪T"rQ?&yC bWg.צrd]4lG+ʊUAS.wՀR84t]oC=hw?{׶ DOy\ }k )6JCH7DH`l'ߒ/kEu⮣xf:3{{)7P3VҊ]4Q/Rq0Za9%M4Zw!aN5.g(u%A<1Jg4l;1bBv*XY~893PR=gSeª_EYr}1}? ;ι iMLJ1pb薬x%`/&`b ΌMOG|jb`ԞJf BADHy@#<']2JSr^o7)?4VI!!m'* t_iUrcBE9JZ% *irMk4Q3khM.,o2 (A5VK>Qe!_;נ*!`n*叽f~aWFB)aYfCswJ2Jœ뤪a2$NlDpddDzgqI:톈bgC%/];ZnE{(f0mYRaÓk 4Q)Jl5X9q alV2^/,G;YN⟡-w?ĆF>!|v9E䈆UJck.2Lj_]?x׀%Kaa?<(dZr7~u{L]X40$)c7Rzv$ d;GT-7J'Pm9/^NڬϺ&mѝfN0 8N.Tn8 ]GϘ,DpI ǰLjwh.GNƼㄔpBP5$|mu!-rsbRf!gΘ3p;j@}>j@M-9d8]M@JHtF?uj|cF9Jx5,Gǰ: 86^x>M}qlP8$br pUC } b>g'O3w, P`J,D`Uv8SOF=]JYv(9s@O-=OJզ(=5X+&ʒ \ <81gW̱8QEF2-QigY%؁o3@܊&so2.4<+  &d*YT<)H\" >L7{h5 ..ֹ35[og՚G(yիeSܟat:Cb3%P3{Z̰]iL\%CcCtAW]]$KO JBF9K| (ؙ.W2KsQٸlT[Y`1 ·C).x p4_D$r>ʘ+&vVe&6Faw5īv%,4[P )RQV(pW)\Pc k* G_y2F!:-qӢVjHcQ܂{Q F$Hk IR?-Sysa[ʵt1/0p 4KBh$}qKͿU+0~?-yURSB27h*XI@E|gkM8[BjAZ)gZز$B FP4w8Š :]܎y~/^Wr앆d'L66(VМ|h7KkkzުIoZ Q3pn} ַ4[Gvˀ$:ƿS_)] s/)ͅ4/Bʀy͞(` xcpI{#!IdRZb ($褟Ųێ.ݡKVLD4[DX]$EE@,v+7wLf|+?afe ]ϫfu$?zr6| e/D7w+{VݓAf)O?\8U-PhpB +7K1A},beg_.p?^d?%B[oPK!w˟;word/header3.xmln0+ M[i1&X@ n*M80x<wZd$$\MF^_Fw$򁙜)kDF“ՏY9Dm|82Ry)4c-9Xo0VS[ Xuݗ˅354‚f[FHw,ȵT2l  L#F{AmHԛ!Nɻ YX^iaBP_Jwƹ4,H&juK&`As"?iS51OHG"ߜͤ9$>h7~p?m.+o;ey۳K V_ĬJj.7[+T%ԣ&sl61`m|>{hZ7#q<'{BRh?CgVa.rg_oPK!"'P;word/footer2.xmln0+ YVp Vmeh~IJUp`x͛VQ#`rLc áfLfykfepf fz^ TKC4\\A8/ 3 d4d NCNnY/RɰCv<1ڙl@Ll/h0c;>e„"uB0p!WhZ.ʱxb^$>#q5G%Is,9{#n/k_=ey=C ӥ<U <l 8P,]ߚ,8e9)riz;_ߑ[輿^h#~v{pDjNfzS) S9Y].W?PK!O;word/footer1.xmlQo0'; '**RM:mZ>l;$&Uiwۇ&i `<erJvqvǒ+ Wݯ?Zuy1l˂1 keE[-Tq.r*-K~f J=׊F^94_?#Q?k턁51; SLxICdcCEʐph [h:-EGD~yHmb^Бq̸D5'%Vhw*9l>Ϳ9h[rdK ׉yhe9@lH,]Oߚ4\^ؖKwed7{ysʟ.ooGFU1lf<ŽQ SGtPK!;word/header2.xmlN0"߷Nض)Bt!08Ncl'o$MJ\d7=WJF5w^dkfryy]9HyF6ܓşy0[,#e6Գ+c%3ǎ(1.qw_ƽR7kǩirq ݚ*po!BBAv<0&#i)VPo wLmҰJqqe[DdrZ4{1m[]1>(z_W[sg>9wTvOVmjX}OTXZkU"lY5Yecq8I-8X;$׳tCx,7޹J:6ch 2#r]iWPK!n;word/header1.xmlo0'@~Ol*ڭ(v۴vkL_:htg[ܼr 霑DZJe7x?N-vVd+Y~m;/ RsJan\J I;%`)<8!CT?my #μ9/-NV 8 5?CQ=)j¸4`1 CLpJ]ʉHF ΆZ6>Kzm5zZ4;+.);"=bq9'%+{H9:c~s^q~kΣ_"o-'ozc'd zd0=. e:Ͱ7(_b6>ͱ nx@ y[-qiuA~I^J tol}PK!Kuword/endnotes.xmlԔn0#;  C-QnUyט`/Mh~~v(JS9`/߿a^y6LyT1Kߧߓ"å4AjuS i!L\+Z!L9#Z)ܗyk3ASZj Ļb p#M**@KͱO9/]a˞YUZb2$\6n=9q[TSa% )* Eٟ*bޮVat RkXF9g/O8qN 3ᘉ1Zs{]6?ZVjh[2e<X $`dts5ڌ7WP5R#,ASN2 WazFjm\׋_z4Ui?jh@n1 (pn)\$s(k,>*WDf-U֠yw2Q5GY-KW7hN4hܛ?PK!word/footnotes.xmlԔn0'"CUԻuXC8!r\_ͫ, 7VH<H\UF5&uT3̿i8nd(֚edNв5`,n@P(/mqk1 diBeFR[ %5/ ]S'E)Ѵ@F*b']6ys.K`5CK] /4T;TYvvf4e<'ueib1=Im.IRkO>em{v^z?ڟ`|X,5x%KW }.1#Y]oMWNPnrM u`DAjKRGxtscFҫ]3EurۋU>jh2P|0~2h8$w((7/VH8{jjU5h]G{@9 zzߗH[&EL-G;բPK!;word/footer3.xmln , J?dũVMSVǨ v;vݕc73F$2H+Pv?-IBVru1o2mZ'rR2JajSBY*!i ,e dۆ24pd CMxToJE61l@Ll'h0c?%.d 6>#RRp!Wh׵.W-.);"bqsJ WGGst<z݁Σ]o"o-'ozc7d zdp9>2OI#vޛAo x cWa{Zʒ:'ߛ6\d't1Êol}OPK !uΣ''word/media/image1.pngPNG  IHDR\sRGBIDATx^|$uߪ3Bl̴'7cc-qkxarZ8u0e,Z2c31 -Ƀid~[U]]U]WGhݾsգ:}ιHz!vז-Ϟ=vj OW/?pH"@:m1+rwp-C7-(hanz C@J D cG?y  D=N0x?zO>k> x5hF"@h$0yaJ.|ξ}غZ1 ,D"!fzFz2? ) ~CVbLjI6\vw{![;- W.|cT3=!2zwv]]̙:Z}ʫjcurv>G/~ߟ| 8 hͶ7_?~n^?z;w L"@ P3 C]._Þv1+9tu76h)YT+}w3?>*S8Z3S<Gb'ߺgvZOήlΘ0?FɅmى.Ϳ\[&%\Oޣ_] na,02,/\3"@#EIVxybXVaLl"E? >Մj6o7|~ݫQ/oΞə\grrΝ%p'ϲkc1/*F D40T?q}aQŖ\bߝWWXWXQE#M;~JjV k~M+p2cQ2wz,G5 bmsF`-n-aJkO>y~10ПOJspOmw{߿_P1HkO~u䈱=t/rp2>E9(T˓ihF8!D4k-/a B/4 />;[4B̀;"_ Xcy1R_o˿rr_^q~u)%G.DWāG8r%_eߊX@e ~>?ǻӔ{sŽ^Vv{v/9{צ~'mO3?|=(gϞپM o -^g?w/Ogl׾v5yYbdRYR+1wRۘYQG"@@- ` t5Ƽ,?Hc!>rER!{4I}|9e/~7a~u#b]?4!VԖV. C5)AJN @K#Nя=y,Q}Ÿ|{k?kh^ᏞyIpLsL(̚)҂[l?W·tm3d6 UongtYX[$g@_! Έ> /<)|&˱y? c1}n!E[H2S m^_Ykm_+x./.@OW6\_pIw|k(b!.FԬKj:*l $"@. x殞kFnx"F34]-8"wgfsg6Z)Cck;Y "Çk#%hG唯-TM=|r}y ŊxR I<O$M zl" zbqQ8W@3̌/߰pMB.F3xYFI]X&h[H3ڨ# D6x|tA~ rx HqDHF<Pbk5r!F 9YORR2 ͯKq<Y(.]xᅰ}%P‡" ۮ͏`#|u||gaI , AcD)< +I<#2=K1:~n3=rͮq%)LC[QO"@@p{F: 2)}|͋.[nrvc8DzgJx) [|o{3;[W0uς S0 EaTOI 5!P0jMㅀIկ~ o Xl"_UK(̋z_k-! U ٠MM?T |2] vǝ.]_:ܐL7>dV7^lP/"@&?^VfiJ7IE)ǐW<P <ޜ a[p(ݰսQfV6{>;;'FX'`7 CW'Z{ퟞ_QuP"@jB?,uLkfra[͆>6]8T,3.YǞ//3'*wFO@hiD- jX3_ @=~#G/E$C"Mh\}j1qAk߷%"u+?rL6Q[ZhEҟhï[l>{\+ޏ6ЙoMzil><w}xA"^ 65M_d mW! ڀt6OwiM81̋!TBlADpz-7B  @@%  D7.t;#ψ8?_:kfba&BX1hvUCDX*yF0Lkii͠촬^0)OZ@oc??7>]a&τ[z9|޿- amyRa6> 9QG"@K0˗"70<I7qp'gh z|v<_\gr@lUTull!*hodaյ'W^_ SWvmM H)ă\X Ef| nMǴ?]dU?sc?p?lh=YQ<j)^&$D%QWMJ+N=Jknbͱo/̢pM$f~В<1%2D4-lILGY(W+8 Ə,PJS?ʗ4R@Jt("i 4 D9J2tU-/r`$YrT T $H\}4^u gc&|R5: 'DTʈ,|/5PoJFb ).h- nSojE]W/- ˞P20KO*웚]rnu'/[C}jE5g57'G!$t J,Bp'14IɊD}a eTR! ~Yhd>ev9+uFY#&SU.~u> FƺdțԼK=(٨vhF==%ّ ed0JfaLzYL@~/͍MI(L ^p W{1869 ns#:X ` d 40``GdrՐeܘ.8ԏ}AWK hDT*"@B2z 0&=%y( x3Rwu@$?"+-- n(Cs%rBW2)_4}Bdž%S"04L"@Q{zd%p4 VvG߃ 'ob~z.2H|NP{,/Rqtϟs7L 576F "@%D_Y&LiG x̋FJ@1{Z&/ )٣e eӛ<n#CP S>M=g a"2=!2OV< didp1n5 5~s57`A8BakΓI 8T.7`J7.rR0>poXKvieVdEG~֩O+?$2;ew?Xp$"Ј3=P6[|+eARL ]!m 7wTIna=#o{[1wu!t-Jh8 DQ".Zbg)DUQVfU"{̋Ѩ aLa_?ﱛ' D(madB b| X(9PtGukyޣpg˯@@(%F/,ԆDIà(Il?  $@`}rgOQ.4O@ 4K #D"@h+Sϗq'&eX&SU/sc%ߊų"%D 4¨9B1W[<011zAsnؖcuiE.n.Q7"@@;h!m'%pUm*}l:5'jx>nT߻6riֽHڏLGn5`EU2}>ٸe‚}Q\<'*._㉅p8oXmHM1J.GLirD78@kD*9{~*8|]s5h<83r-xԉ[nP|2rC?˚u c'<Zc{Q̃9;?-SkBQr? =flgp{ǞOv]! 0K7K[ͬ]>w<3Or!(6t>`[X UAN|qE3D3nZLϿgzv/ <qw{T +xJCzQ_p!~N񺟩E4B^獂euFI17Nau@fԇԗ^M~a{r~HQs:Q47?ͽŇgOq=tjmBwm:EynUA| v!׆,oh {}$fM{JbEhk.H_Cg_ڵ";t2uhGIJ>%?Mam?,T>`F˺һ_('& P ٮI,2ܥ4n1)N&ϳ Ń+=j 鯍ʞ΋ɠ^Xnfԇ4@-$gR&|$iu3OHpeNqdgwstUW_gae7_d7oCw@E gπ mbkj,0Ŷ]sW:k^/-ۿڵʑTWa\&źE/) d^)I*=EH0@F.m>\pUH1`^/M12a [:5G;V.q63_`JACY7#eEݴ.`lW8@TI󢍦hK7YmR^DZZ[58)gz^}-{2XI<]\v˵kO9v칁='_G3-rω;܎2)lʴJ0SR=\õY#/O{,po6,fd+(C'QJگ0U$%@eJ*Č,CVa!V(b g ӫҌ՞hVUc?nt8[h!ΓVc,Qihq1k0bB' 5'PEZⅡt|H {x@>3R~lq)߀mٌO<̵W[!,x9$mEtxhhn J[:k=sXl*hz-&GࠨÊ@% :\uGL0 *Sm"z-g7)`d>\ϹUfoC#AY M(5[^,,\HP̚xbWD y -1ZN?P2FSG\`j Yb^kU?/I "pAýѨy-2DkcZ52!@͍)}v&\w[x3!0Gv\!LxW'ABOC  L5W}:tt 1![Єۢwh"T*=trw7rPi+Nb MQ-YVgLGZmW}[ w39tt_9 \Up&UȘ?Oin p"""4> Ƃ*0<s0Mk˞##s(sĤya4b9Rۣ@|j%^ % gzRA#SS =kViH# BɹԤʹ siaO?w}{PT#SɞB"OxɏHעQdDGC0ɑB>YDK R"CXˤ-<Uk~Is~^ޭ '%PqRy ^zz`';C۱ٳgyyѣ?ԯnBҀ,2-D<џ?eQ@ \.ɛr<2q8gQ<syAD1KY:h2ajegJk8y9d~ГgT7:5ali2NM Ky5WKԍ4@%aC3Ka'"g9CCI6@a|ˢc{;P0jG q<񢆳UX8~,tF* 4O#Nr񝉸I7;SG.Nz(@2@= % D!ߚb*5>qi_Ũh0&"D-x٭*ԏJ Q)9GN`m\B"@JhiMMyyg%n)I u" 檋Ƕv9b^[S$5q$"@:@#, 8s|W *^]!\ gCeZ\D&Ο?_\>j U'q8=Ba6@]~eBt#ʘ9wSD0՗WFj/VHB@*0#PD1>e&O=w|Bk1|bO[{c3ǐfUEV@7^!| ,&8k,=-4 WۃW5״XDi])zK7,h&8s&ʴC**h4 pU,lT,H*x<+cOGk1HpDX Q2\ei J,B:nE+]fhqUW_Z]}򬄅Xo֞iojC#&}f15 PU.ٲ|;MUOA[4o8-(2%= ^FVziav=yj^-!(W,~8#W<'^|0'Vhs!g/BMj s[V,dbD4W,\SUfrm206BIUތ%X#,4_߸6*"PZZc@qW]fVU]l΀ZPS``"gP }%s5tDyuծeڶ]scݮCi6.slacA8~Y*M޽{+02,DBDhmx^"jdDA $8ő1UO1ѧ]C^KaiLK7PpX7[NKֽxW3t$rEܬJgg$fQj:e>>n K"_U58r0 dž nTbd,iЄKMQ1v%BAhe`q{A YAMbYxe܉<`y ΈH]6Qeh tS)b,u!$PVU!i3p8|F ݯY%$aۖ 'o#=sՖU><P oB;Y*ntlAg`B 1RqsSO>打hz]|ůz s陖 UƠ̺Mc[X^ւe`oU  ~= ,bRUE@|si]T.ݵK1e\5Pt9E@%_;PFV< U)-O($dHЍgVQorv5zeY es-c9O> o)6,tx<52=! gOY<BviN19ڵ|[O⑔3C&30;i&?{|LpH#CT[ ŋs룸E<VY:qZR92b\#T^MYFw\dJ-ͥXFjId1~d;(ϝ?oS<7Skr7Ceg   B`mOLsSWo5`EH~ӟ+<|_.F|B': YCQ0'tpjs,_g|烾I!<"Ac^!P̛ES+ E@%>Z8N_sϰ[K9'⎌=$%8䋍^BJrO .(~(c#4}Ot$Y܏Y^D |Z|l`G+?r9qq{\y Qe(#)|kRHhr]'_dYfIܿt Q+,͹O\ɡND Q"[bvvvx”i k RY!r30<17 ԗ;Ioz:BQBnӑ5;gK?ǂ{͍w;o77|.,fcEI<ŒT T7f](MEik, @LM#ehu W=θDGqY-  uHՀIpK@f?_wVqJ  $`><gɦ4/JcD\0d^D]6@3alV& ξԶrGZ.N*$@Fh D"PY D"@jO,3%D"@Y DΟ]1RsgVXo+OR]B :.5GOqؓWY%K֒h"PYDTA5)S-U AEIY2[?  nU_V1 &QaoR$_NAxƆYF0@_Tqh(0jD"PoQAlB)5[P)((3qlvPAʹoPɅ9 J4 MQ=5&@F8"@,*)%8h/h%!"qg{b.#Ds"_<3dqj*ifh\ETVߵHg̠.Y>뚋!^`Ae41F cӼDTbd,9UH(JRIMBA9V84ŐD?SAB $Jq' .4%"<"RMKeS=x} j5x=c1UT*b+]̛bzUS7"Pcda(#D_믗s陖Q$Ux`}l \I˩ @X& !u*cٚļ#`:,lVAhhN5*>N."q843ǎ+Ra?{ vCB5*n1"Ν| a">x(7"3*Lȩ٭.3",C9JbkD hKl2а*'Y*A_lTI/0xP`r;#$ႇQ n &RaD$dBwxE8w%dzUeMx(| xara_/;u˜ <I y." vWF7saY:n UV$Q0ˋhf%{>l`G8? "3o<2 #( O1:4 g:=Ɩ_*.nD$uY0{J'iDTI2c{;pםW^oE]T[ ;`^ENV(tlκU6F)sԝ%@>  hyb~YqX ǥ {JCKdaE݈h^+q<.f )>bLfCD0nZ@0N(yve @FP9 D; -_.}g#]TUR:"@@PWpݼ#n-W_9<:fv&:j0Tba︶m\z;qɫRC'~pnpdžϡO=vWylUÛ@ kr4‡O+2<h^W#oڂa/!H+K_Bkb~(vZwnEir,"Ӛ@J,_᭛61 /~~sd ׮^{/'vnڛG?|)[h[g.!.,sfjF ,[_{5v%` *0'eU,lT,H*I+Lse8lOûjg0 0VkQDe@UiBu⇌\kX.Py*-o#^}W {&5;%u}d4z9\,#D G ?HD ԄyJl,OLN+jzlAͬjl6sҤa*0ogRJpNj?m&ͨ(sp3O"oAB89ϲy[ߧr%'!L04hMÇ%c>NT ؇8Y32h-1 R>h1 U# xgp]`fhEV iX^U*Bj I0gb.\c󫸮8f$/+)<'"P= G!#a">o~3/[eLs@}M Z$9D! ̋+lJx0e'_I%*fXLƈTȢ%P*]AQ≂a\U 9[ǂ&Q 1Pi26UefvV@}@ P]#%D. d`__lٶ>mk]?%1 xomfG#Ju#SX1ʋ@I4Q+ޥ:Y~cO!AT%/0W3I1KWPQ&YU,PjmlԵEI$"l#(ۦwAȃhQO} gn QiZ#$YćQ\4"`6//gz 끬 ]Q״VY"\e)<O9@i=92b_<08%(PɔZl "PY!D9#\xkkkUhxBxYhXŔQg;r6KY<(0CIoQ V}@CC!6Z kLUI<y碂!DW)mcg8A/E]R. Lx'l 06>MMږ={=Cr (cP0egxD?ҟ܅iV$Q)1HQ@=(60ʏ\No8p+o?ج!2=tṖ)(Gō:d Djms<$2* "T`EҀ `9J~haM0vO06R]!jI aV#J¨-OV1aT"Ќ08Q܆Sdx;IV&PK C?ȶFiYt'MNĨ; 8KM%u Seqgݎ3U ~D|QYHv!Y޹LX|%F?C׍7*DJFI2|sc{;pםW 'D"K~5Ko|K.Н]|[J7  DN PyĈ':2uEOLGZ +}mv=W~|_{_#P9SQVh84?>S_;}[]Cl'|\hD"@\yZ}[È d_C*8~vK,#<ʯS?VCY4/>~[ oY_ p Mݓ}2Z Dޱ+?=}e.YS7"@ CLD׉N~06Þ.\SXNwa|5M>]`@r_=]]i}QZC7qubc_hftDžVJFRՅ`i71V==gFd(b6_b n֪eiW'IBV -X;-}GYZbņju$s0UF7 > h`8[mpjy#yRCIקQ(vrF@-8p̙3K._/_}Ÿ'+ TIqTVEjc K(L{hذ,3ZFW? 8FI@hE~%/1 .ܤCkXmͮKߝ,S+牢% _G~aT "Do /P#iW|?K. 6۾&UOůS%NXr( zCI~:]DjX0hZ?^WRAS} dٽxnJ *|;q"hruNi Lx KAd11w}Jmh8 eػwoF!I h/F)s؅dFO bbTLkɋ|d ?HO;X. r*ofu]M9J-8^ˢF ]DZ2~΅NPՇ _CK_=,^mM`m,l?S~Y~?Z3D"Bz UUdڿeW*$v[6S($=E#|%2O}˚'J`g;}GΦ>D&fJb Mf]i?'[3pa8!5gl<dZ[)an CL._ $-@£/>P, igӗG'vb[j\ݹ4ρ` .̽̅œ`_QWO.* 5$r]*%] jRp.U8&<>*rN."P5Q"G|V=FMۊrOfCGnm9+ǎ۴iq BS3>½=WgٰƱGMbAȦJ7O>NsʷY?8r`p'άO@vsD 9^e#&EQwK."P=Fs4INdG뒦R!D PԼRi4 x=_tG}=ޗB'W0]iO=Y s]ਘ^ =%fs ӌ>'|1͟VTOS5myS&2}O>{^gN&LmH 5O:%. (bΣ4NF>fn?Y%:,L{G;'obxm4^ucD݉=3 Kjbhr!>ܿ j >ނdR4gݸھ s|fY,DI,``؁\r%KVF6@,X7|.j$w*L$f}N۩vUxކ#sCeRvY Qg\iԟT jDzhy8K/F\q)3b!?3"PqvbntbF%D] &c.b ;FPbq8I>0nzR"@7{G~W\f&Ch69 Ov6Ώ|P7"М*0؋g\ٜ"@hTN~"0Z~"@ D^0R}^/I. D"Ђ*0TS<ߚSF qR)b"MQZ)8NkE/`)+"bsB4[eiU+ `J1|aD`('#82MdzԡTbaH^}5幏vtDžK<=!r`P%2 Xά Bq%[o,kɾ4.kHe ؕ W /0h}엥O,O6lfLX]tTba}5{nE*[xE ppa4/$pMX͡فKW?7+ F\͎;Hxk2"c$c$ ǔ PAH u%ÅYaP|6<Gb g~2*8C yBxDD$BVet>n)eejM&FˆMSi( &EIYb=_YdNKR]?Q$h0p4@UW\Q;ݽ0(J0fdJ4.6bY0%h@7- \)ސUԡ0U$%P#:b"uRDžQ5-*7irmN&ǩL:RySlX= Taa\퉅VEF0 Y.7l E'ȴ%4_Ne +KYc]c`]ԟIZ SGg%<B2pOZTKt(d"cUjcŠ^W."P- ?~o|ϊ "@ 1/p$uߐ_!ۏiÈʆo䓪161#dtQ˛1oOUVw(OB&zJ-$ .qy.:5s>/R"PgGyG.µ*4!lV,/߇!6|`{ *g,`ɍIn@N[$Јi,bjEU#& XxAx H<CAF۔klaerW TD  ۯfAD<{Y^^>zn+1bNWp}Nb_agyya`# a ?amUI!gc0#C^GGE ^pjcXMe.K H-0{~{aGD @`}ݘW߶ugv>W]?{?knwy,nSb0=jgEmI22mӭ6'fۙd=L3J|D"ЄYEjB+V/u=kq4rXIxe;.6t,LiDS@#VC ׺iJ4౟ͣp|O~¨tUA] 9C D&+$_ s]}fOw|䪷Aү7_|nqٯ¤x~SO=%+ .o?_O%˧ϵ/jQ-Yd`޻\\?Oi|d O͈ݗ*4P|$s`~9/2<]KY >{ƣ{2 DNŇk+|&xo~#]`4<ڵ_v2+?|\>_˔W`|}&29 -Dy#b WyQ$%D6!,Ʀ\bKނ qgf[^๐mڄ/_}8D3B D"P>f0ogRJ͟Ua-PYAxr}˥MsΏ8m?Yz|44vt8tukgH?bi%ʴBk`rOY15ha*:_&'4 ˪ٴ8J1*kQ\Կ4!udϦ[.賗i>o~PJ@Hw,pQ^>39@$p3g[q viWxR$wn4P^M*@{Qd%o_,ӂqkEZigb19Qw UT$:q%o)9*<q,>[-{w{펟D#$cr,ڐ$K@X!%5&2[ay"Xt7 Vx.NW774Ah{ n<"O9FAS<!1# GCuFQ@b8+Zqn)Ti݈A,J@ 0Fl2W!k9UB/U-cJI('w8TK3ҰM5-0֐bDTNA9x2Jh d?+x`AI*Sf,ͪ/ƥܟByx  5W<!BP$ @AC+a 9*ogv/isB4ꤓI(MG0^NT Z>h[_|믿^lyvw̠i~9ׁ5հr)cn̋Gjj< "VˋXjhB UL:dy>iQ3Vmh6T&p*(l[ vO%cǎmڴT$D90fB 4'[g0|r*NH0Z{@ZYiDpk^p$NkQt\ph] Ģ,5>ͽ r=FL0xAx 0 -$Pb"(o͍!T'Ph";L$޲쿯]}^zoHKjU OU/CW}+@m;F1omWA. l9@B?,IDL'UgYKBl|Gaup9v_<2 &<*Ddh 8`볺 +q䊖4 ٓB![uvr[ Hxz'sP]/2x+HZ&TLh8_ yJm1f'QcEV2'XӻaO}C . k&p]Qjnr]RvG5o[pr}`Iد[éy!|T6rd+L[xt,){| ؝dX<\1kp+^f 殏d0g*d^պ~aSCܤhF$ ڴwü]v)Y1a#.ii)$ ^Fs8W4=Y"2+<ՐsLhE002oܲN'eAҶ ۗi?*@.r>L~+`c.Dh640~=:%i4hNC6D$!DImc:<#Dfr̓t[oC]Y%WR`fI?Dn>1 w,A7sq(;|vaJ[AQToO`of~z2ӓ7 p{;f^eixvB[C `*4=eՅ/0e^{0*m?>׾L!|T)~~)c5DSz(F0_tv !'ti</k0*Q?<Ch{-O_ SJM^~\7`[ 2< ':RpD,Sd8Nj_ l24/'T*<Ba#=dhGaQ<(WJ! &H=M/AǮ/+H6 D 05`Cܵ^@߀oJ'K|•QRt<<RΘ}rq4{<H? :Hr gƬfU[YSF"@@ M%J2L]61C>˽Ck Bb`"5@7րq<|AL# ea4dZ:Mi47k o @<$āF,1n&D|bagEbآm'#Aۛ"6!jvqYz \Q3myzbc*sWd_q0O%&ڡ'(i3gJFD"e$d5AS1WyEE\!;3q\cOG^@ > ׏S# `9vu> 9%vuk! ?om Xn^h,othJh-27%YKhJ6-f?ibLD{6@s,ߌkf"֊9/km%ެ%3[) `Ur :$r;`m${KǯK#gƘ;znx*Rrn(cRx[viPPVOOM%b QuzjݙH 6NG((WCOJpa8!KME6܇)Rk+.|P%Ogw8#uW*hxo枨XS$ُ>ҥ`^p,ݽ;q% yC/I'~7$o8Q"G|n@Iޘd~Gvc<e!ii95~W3c ȳ(OK-v@H3z T!n \;/}zCJ²+le;\ ܢER8bvr.~YfrvBI~+=۝PQuzXp{ޟ)Z P RNzKڙ%& ρԗc.0)Z,/,ً^>$9 =qwȻOQԙH4}pX2X%)b~GD.| ?!R!l5:d XM^bŸ?}cީzymVLO no;EZ 0ZND (v d]v\ʜq!Č'+ }!0Z饾ʨLw]DJ "mӜfᠫmT lWsR.,EvGda&pf>Q(PJ- !NC?H,u9!&Mcb~(IbɜT8RPLl  K@-K% vwӃ#eDZ0_аw4emRO,J nryo)ejG݉@!Mgah%E"PGzz*"!@Lف\W,qx08U!vGQݲ< ]mWOq#=0O\}3e=5I"ѭI< B`/In yH Py-t~3 57{߁# "6yuZm06_JZ Pg ndw5\b"yіCpO, SO"@@G,񥺞90RmiZY 4᥈` + D"g8iqhv"@ D,baKPUavu3 D$,;tB~S~RH)"@ h. ͩ/ DPwDRS%XO.(pvԧJ#JM4)=i #\UjL_YBQ+S1D(}ST0nZhE"uK β &UuI(KxOR@O BNZz"?SJگZ/CeTxa6lf2C͍ԧ4KQD x`C4H@jJ%4fcRƐg?0b~X&+qm͢IJ, (=Me8v&D10/>f"ӹF#ۼ#@_Ly$p\c]B@/i O[zH0&sAFˆMXr^6)Z@0 دQ}T7Lì%7wl0=y@W\Qrh(x7сY^1!$ OPc JRI"fdJ4 ƥܟByvg7d/ 0 (J0{+f0*i%!GPY/_cRl"1ӊll0 F xARL 4OjDC 7 Yvm}l?b42 xTF! n˫ܥsd. 3Ik|AZ#謄PEbhU`.uL_1FT i+^M+Q98o p񏰅VC"3/JB ~/+,fZAc@aD}eLj9deeí3P^T%b=]e(L]ەYzgi]D9rG N??W(Hu4#Z Iβ_d|[8 R%\>v9!ҭ|>ZBm?{ T^mH,# _?_iݓ!j9QMdVƇ|?ڼ7^,o7[ϏX]}pڑpIXX={=Cۊ f$4( 6f!L"xR,rPSLGY8NR _gpi0%yy0\%%<*_B^]$,?1vZ0z,0BS(};@[Ƴ~sgc*9j`>*71WpA28tO6uׯo=g>l=XfyǁsY/F}`^CkO71<.nu Oʘ*̈́F η0$HÄHC.|/)ؒI޼Sg5e[0wh9+uw$}ۏ1=ϩ?77Y.'s UxWLpC䌑ϕKY%ϪPp$0FTFZk~Y'pqSDXctv0/^+~fܩO~-/÷~_C=D9~1veLa@_/XV],{B)pw)`s,xۣE8m':aC/]ҕ>us 18]GuohZXOAח1ߊ.ڡD6 |3K ԍ8:QBNnn&!-C-z;,Os>~fO顓S o±#K?cOy.6G[V|}x'MuaFx6cR;|&(A(Ysb9x4DKgyQO&*߿Lb<d0[eB\,;.$u+dW<NU=|={g~fog>̋eD??Vj8L#bx"qkA[amv)~u |BG2M"@Z@;[ϻDDڼcRtԽow#߱=yh? ׳~"WT@EY<*}q2X]N}10F@yaN jȲ߼3E= K1^7Ӕ׹1Xl56kfkDW?^gGRȍIՕSŇ_1ŷr~Q?^ꏔ(l:MA[[W9 Q_"@@o5?;~#4X f;Õ_57Y]fChbZɤ|,ajCf0;sO sN׫+׿ u"@:@;[3ov]OEdBηһ wgOC褌K?Ov9s.8^on1WXI~5Fmb2U5'evRV k~wTw~7X%Zp+=oyv_oa<(C6t4Z4 B- IlJoݪNM'0xq&d|E:n< WӯUbHoϼ+8SF 9(OB@7ؕj421:T8"rZ$MO-,ӢE!Lb5ْtak/Glg6eal4ul<oaocB @}Q}sT'f~ce0D*8WVpE,&Kd)#o:]FPn>}z$iԊ: 1wވ^B.ALf-wiȉḅVaIHL*xe ?ÎH z!6 60ve~OdBk!d#]'JLŞC@e{kt"wQm苾υXFL$Ͳ(YxrĂ$\y91&2+⿅p$Zu a8YqRE/8߬-|Vc + Xnx1vuNCǺ;6 %kܭh4F¨ȎfaS,PnfH1A4^\㳶~I??c#@''г$.Q-<1#-# e)]D%(aG#>!q!0m~B vxr.~YfrDb:f5򃀆7lL7ܐ9hΘ-Ewv[+ w5β {QO̤Thm[n AuL,T}шfqi0gn6aî+bJ$>۔ :3ydNm9L^I!Ӣl76C[OvTVavhzhJ!D,/Nĉ>%4= x>OK_O gѭ. bҥR}Č'+*U.2~)\B+j9Ԫmd>q&LJ &@FtD( s=\R+Cͧ=BZIέNKl7^=43Zɼi|7>dag"P&t&O'ڙ׃#e t^@>d+c?̋qȔҶV 1b|<_= B*y UT\Nm2巢sH/P $cc 4*pى@x6̾`A `=Qvȣ*sYKf!bH `RȌ9]? BBH-ˣeI l_Oy<6řLQ*6 V{z[}}IÍY*q*4KX_eko7|eu޶u>;~(-ό]wH ' 앚kN0uQj> l&aj鐔I܀OS"@!w3]88EYQ&&\F"ՈX⧐c4;|U5ZJ#S-f0*-U- O DԊ@Yp.,jHC D4@YPz)"@@4+jl$"@h f0|&ЊV|ys5%s n!e?ڱWjV[DOiQ0YhZK&ԭC!7Iڍ2qJrO2?Ȳ w,5`h8<f*0ӎS -G5!';>Q4_eq0 ` C` eKGh. ؎H≀@8~ `(^tُ9CH$v~^/;"IcPr`€SeF(Ǔ>D0/>\xInQ!-pBk9?90gJNׂ5A4/y-vS<PD;'e&ypR /]'>j`%ψ#zdG0pq`A uN@KW\QH[,u6?czThV$[[C^X\"P#DBkCSY'ńNGY 8ݱt/,geb%GbTñ6R꒼ꫠîo:hn"ЦO1V~*۬.a^Ȳۿ۷v[ۋ > /RFdwR ёp=kX_m_c f"\lv*3;[޵L-kaSlWVjYn' @z|rH{ 2=KG)3l6<2E5D/NMʇQI Dy$a苟iA?ndn\TZOaGj ~ lנwڿ3sEu/zv cv=F/ 8綶 'lЏT)?@E{kVO?}Я)heRl4|*J2y|a->k!$, /G}&4!bBrr䌶 +jyF4MU|c^v0F) G.)@}HrЇ7lIXcJ={,//=zU0D's71ʣP3 a̸'afLIfa76:A>w./nIA=X/'6V%|\QҮXvW3 9sYplE $C*U='oϓz_/L@ è!Ǝų=L$X>%aԃj[ʬЇ,$z-d_lK,("@@G|qpDZɽ: !P!ҤD"Fˏaԩ @#NJFZ4~HH3j-V~Fh D"`!PqWcldӦ=x D"#PqM#,GD']D"@0`$D"@ D"~r|j&_J}ԅG {'VN ciˆY%Ѿoj6[PrEK@oB$f4Z5b>g;瑺FF%oK ԭ¨+^N@*Un%n{V_H/K.O7>DiJ7Qx>揿;_bеbȒk/"\G{_ o ;j[Ǘ5O(Q;fuB[pVk=Wv6?Z= DjpI ~p6B TuD&XWN9_]z7EQ ?/Ν ]G=J*x4)*ռ*9j<;O?a/QmɤY+LϿ,O]wlOg٩feߍ|5*+pc[-q Ѭp@'ur7GC ˦z2Wf9*V6n(5oV:0+</ t {~Q'+؞:1pNwK9#U_Xma|Q֭]'Mf5t(s0f0@CcV K7/I%D4@\~5OG##vtP+u#}R? a#<} 6'1 8en o7ќs%zy%dGW ־CHԜ$85 wO~7i{ d<=2T8əSvS';hX:ulNeJ z6ҟ7 kCoOVm݄2a#Y,* g ~h+1޵t3kkܒ~]˟I7X9ި=˛ڮ\|ZIŚ֞RT [yS1 @װ1#\}'[cO}ZV/א }`h a4D"@jJ=Zja.$kϘ V3)]I8 ף0U4=N`HEHZAC}KlFK8+rRV~Q>Pϲ Q62@-?ͯsi9+bw [Rѽ:ʍ xx( O] ؊脑Q!ŋG 2`ɣ ni\C"Ƥ _׼q`-9`:bZFq 9Ѱ: N`I, -K,,G3ahyQ ܜ tﲀfJ|&$H(=ž8abBy<+,~ʋ8gYy4 kH XIz% g'`>Nc2sX9gQ ь&!DbpX[/ٶmk.Mpv>m^^<՟y/If7Ff" Fuh4 D?&.gNNS$%Ӏ <I Ds @ {eZ&$80B DԞYgJ D03@ڒWmJ"D,V[+ DV!@F)ғ38{OcOSTeDRVN/j$7W)"A<.|e* e6hץ.@7/"[cI&,PRN&@F'}Z;h H-LG,Sf|uy! 4!&adTFlH*wRUܤ"qYlTEY<ĺ/asP&VeyJ \gX ,ũ/#@} ;p88NϿaMJ1^(.xB믫L,řmJ2MXd ϑ-p(,y|Ik} ʔ[CA`Z}\",4YhCФB,VS'(@3%zyqگDU{0TFv0EXW.1Q\/]y}R`"/Z*@fq&<ՈfdB7]=*6QzP0e]4 *N=Gb9 K f4T93K >Dԑ0/bsVa8/W kIhxX ˣ IFdz7KLLcҽZX4@TBL,GU1ex<(B%+d*6G!蟘e *2KJ`?5ż)0'Dw0:fR@ >ۊ\l"Qą7pZ~u#,`w/2>8fw2Z{S":'lբ2#C8l½li_oLsf :Cs#&yo4Dӵ8_&O@ 5/LQ '=< (&*FyH =X~?0 GK49S9Rs<i6pYɽyʀt KY M~.)0Ҳ8r#<rW!uDa/߭=eNXa)F.キ"=/-nF 08jg4R@< OR2y<ȼK(϶ZTԠBR:03@@ ٳgyyѣ?ԯn1 4qf<O~e#K> taaU"!8ӛv}% 6S70gS;p;+oM]nFO1XS@,ٚn ˌrl@?qd!MD3Ylj7Q"PD(s$%@6+k mfIXz~wc{;pםohb'b[ʐR-R Q#R1(@cے0Ңha~91ˀ)KcYڛY}iuDTbTu$h ͷES_+ICY D"@jO,3%D"@Y D"@jO,3%D"@Y D ?ލZ2N?\ #e7P>vy$i bѷy"QS69#1Z-t&0:Ӫ۞@3WΜ9S|zzj'31(9GIMf$veՑڈJJ0;>~=$ ?n?3׮$*q`6pyxU'@FhJo /P7LȻOjH믫Y|$KMz6x.&y#2+6FrrAo(+EjG,ڱ$IDԔ޽{g/v"H<axJ.jNzNܹ)P!FgfbZK^FI#yFb}"at :9q"KޞEG[^^ pK,  'Pȸ\+UH=I1pr2tYRaBߋD%Rn,ޝÃX 66Ծ/c;xf_'͇G郻XF*mV٢a%Af>el<Q֖=ޗ2Ω4c ]$)/_w^\"F$yԯ=1.+j;#,㩵s(xl} pœ`_ 9Z .rK|.BX$X&eT۲%b:p,y/%D Y Dy ;vlӦMA탁sS;1 K(L6Wg0 M}>oQ!I D˲čOӻŹ;uf,0X<lQupxwjCD٨R2e<JLkkqgHaOk'MMy'ʹSSF:~MϤD36r+#}cpY~ECdW,{cƼ8fR]Q19)\],1# xKff|pa>fKDhwxL p Fyr Bߩky7XZR*ԟR) є"h]p:0xr001͉;',噌0D~<|/W3r0;<U?sOhgQMw\hs:}LK ʘ1 >0 yVOqqHF3- [ Xc'}h4HK$D4-W s[yo-=w?=knwy{.7߼袋V=إ23QNzbPjv:=ڂnV2Ip-4)f6/0!r<q#NjY-uv0:ӊ8B +=b(Ɨ]=Mqzii ԣZ%A"6$u#@Q'$"@@G o?-"@@Q'$"@@G o?-4-׍*'M4^O ю?bj,"0Wb?NFC I\U(kfSs> ;ũŠ /-Ldat}Uf'p"ky]x xVE?ޭ71WbME#xxɓ[B0+d08 nRjӠ{ h%CYx f'W9 datͦ"o+^rs}LF$?%Q`PZ}eZH":YwiDE(nZp`lbF(q殘?1xFF0k}x#賘įPsCx5s-!/j;o#ɵ2lLAl}嗵yg_^,tQ6D@@CwzgYBP}L/] a˭ԡE9KE\#wT($0mVb~h鈟#nT-dIyJh q 5>?G;Șc+X-uүy Ѽ4#D\|ůz1XD+LR.?O/wYzL9 U/SbiEbƓؕvIBX ֬a14N Ϛ5,GV'D-ˤTQh[L $-LxR &gx"TZ L=bUI^=? 3ֿ3?HQRa6ًBN0@@pk^3?4y?_( F׃#X`9KeEǓ̯e<T ٴ ̟`F^jץ .'mF*ǐS>9] x$3 љVM\i&SRQp !sDCPiDP@dzȥ@1$}bieEi*PzyiW,+I,iGK;=ÐѢq?I]bRP" !@"д_1t[[?WHm[7oΧ;Xzާ~w,x}]o737s⬕b=fQ+$62/ޫļ3u1 ٣N;YqiD u &=]:'@Fh D"PYD"@@( D"@J !z"@(Y3D4 V ȕB=dq\Yłb(SH[sʦӖ`lW4)PkiixekQ-A,M$ 'Lc2,مXkL,W6Z]1ZLu< ˥4݂egpDFI%$OTdͿ-İaQu."H, `"м</(PzpdM mF<ϻK߁x)^1{a71mQ> %44k,0˛f#D50/>\;}I\^ T 4 b`"?H<4u,s"0~8;S @1RhnSXܘo`%9\aɹ߲r򲨁B >D jW\QLq\ThCBg>8czQThm[n rA j5KKͪr!ca.j"5 e] u@鈟[#hnveytQr\;"N  MG0/d(Ǜ^cPKt<"g`\/ s( yssygVǕ{S s8c7 ӓJ̠ R6#:)WA‡2gN##0Aڒ@ ;1ܚ෿\B|{{PLS. |ւocr'ˋ|xʜ+OR1n7*z"v ;Z{w* +ږhQ z48r#<rW xa0K,H%NX#]6zpĝ8pC໼:y]Ż͝D`sy$k!.9RoļHX<mC?zuSkr@;ԫ7HZ={=C bQEL[@}޵alC@=NГ4۰/9e!Ϩ,d܇N8%C$\[ +ηzSߵHb] Χ>Y[ ]DN2( >Dy b(~۶n6ޚO?w,=?O]w޼+B3g{A2[h(_P,^<u,D[0Z֑D\j]0-=¹u0Z펑D j| N*ܲ&[~'@F"R2 Gl}ejD݉@' :"@@ Qo$"@@' :"@@ Qo$"~rDm kRU£}IGJ` *}S \"."% +2coq s(4 VQBJ,%D4bjXUVfgxq<%uQ]Pwɭ@Ɂ&G?-[&<! w'K[l*VLYrE+xrXqqEzshXgbeꠟ}Bk1|P`}H|da'";`Uk'"^`_]> 3L%{mN\`}eWܩD?j4I)$@} *ǣ#}xф# ‘` ˁ-}FMic.O98_ϤJd]d ,u#; J%x.V}`% H/竳]Nou`=+wnI/B6u/0˗":Rzg1lDvx<>'Ohs!`S_ow߬GsJrs+#/$;:K9_whv}0<59 NwD17|'&Pe;!-v]І@ͩLS[3ޚVG{.[$$£1g䋁3 1b藖!> '!"-cyYnpi.ڷgk9aeҚВ|!dT c7s2xD-v]hyoGK=7Y$D PK6~3kH<c+wfT3SP<gl ٖr3*;#boqgj.枮\d1Sd ,Ye#D9YǼZa8D~(7&-|$<u1x?*R%D$E$<Vbb Xbh|KAb^J@r)-< @ʅM9b ]ARUhp Qs$'?zÙ0D% . Q@Fxt%0\Yؓl2.Ľ>Q`#@Kr-verNJwdq2݆EXumزL[ X_^0m\|Gc3XpuEÈs u֏n=fuk~3:~44)niREI#L]qqZْi@m Q[$"й .IY?-+ksF,4? Dv$@F;UZ D&@Fԃaԃ*$DdaC"@ "D2")҈bkeJ$eTio1d7pc6eOߔU"*ڪɊWB|u9I)PtZ@N,I_d8Rlda"<|if9*]Mf,((7N)%US*%H0\]Qv^X$ɩ>EcA}z?gĐ%HaDXyhDJ%x"zYb%{Ń^cI<e837fޚ̲:X `Sy":N4K2cRa} *[CA% ^.$X[BhD*$Çw7oha_!CWFegr# +`xMCȂ>&O)E$)qR`pwI`ϰ묽8b 63X06K!^<ָKmT$RΔԷ w#I@W\qEKY<*K0-.|${X If3 7 mĴ?}0U$%"x|HVIUg(.ۤ8|z7K@_녔,x.|2NJveZtCX]=X;CY` 'fY£ʲ̒(oL8M-]̛b+n*hH mE0/qU` $F\PS<r* (:+uXY^Epo?6o+$M vOEƜ"i6\Zgwpԙw +XIi@h~Y/Cfx`> Q8Spބ{x>BQJD"@@YsNkvy1(ߢ.Kf`8fRseԖP{(5b U6ȩٍ[0#\f4 JZY-~I}"^9#\xkkkUr}Z_6pp3~:Ct'I(F@}R K 3wRsIj/&Tap`S-E6`%%X,1_/c,BCLW n2-={,//=zumVE}%!x0G*NI搗/Z s8&$12$Z4DfYI$X8N:vQ2=Am<f^ ۻ;\8C=y̨ -\ 3 .C BMljADbf4ҕWe+m[7oΧ~QKɱ^sہLb[ʐYJWQd4  n@jMʒԚh˸S M%qFj@s5YM"@6VxEUGV|`8 i9da-#pC"PGda.&D"б[O 'D"PGda.&D"б[O 'K@=1"@3I ePOON; :e[2_b DlV@[`ƪ I<B@(KBLLH4W yiB@# K(jLU]>)vޕ._/_ZXŸ'+ 4b=%&cAacL{h0`퓇jB$̝3G9=C? MH!@pY+(n8Oq& O,?x̥:{D8(%NhVEQIR~U B:9n(OF zCIQ%@F{Z9hWvZ ~B{W\J²k_ C(G[FN!lWbt 1j* Q\p}m$'"FO1]0vx-2QӾmu7boAq{}//)VԵjw%D(4k^%~&n| ɠFQ12  O鷼 tBb99BRŃcFu4PN}, Oj_Ob籝zɹw]ۺw֣Y5gFYWe3 5ph-ueEL"CdmKthDZ"rO Q6;3x)XWVf;3i`3O;s_Ovb~ŇDKeΈ }.\r.J~,,Hޘp2,pblɜ7؝t^^ִTkqda $#<ӥyag>ã M =jڢY3 ? ]fEbˁ: n/#P7t<SCG^y"n"2"{ s%󒷧K1Wgda0'D!9#\xkkkUhZĔ5xU7@KQXu0 .`y ڭk8*&' wbap\24ϝL1͟ILbN} xh;Ź/ˢX[{jm 3y/ssEKmIYxWH'"@%gϞGPn6g!;{2wŨ'tnuzΉ( y 0rF޻D.m[ (ӻLRw\_1"hs:},0B9-s̀ļ(L"?YHD;^p.S\Π} -~[P&j(Bۃj{VAڒ+ƺZ㶭fӳ}s7]wޖКQ]enK_fn(fK5.sH#lzE0nD!HF\qpXiЬ4M iD@ЎȄxhq l .!u/MO発QԑYuK fblt cCӤD"@ڜYm~iyD"@6Y&%&БGn*'DdaC"`R߯TÿGG4ɖnPl?8seu*Uy?A툔SyHhFyjiF@!3fWTTuUUXԮ  O D`  ˝.c̼v`cBեuFZ?!*Un%n{V_+[ohh_ƕ~ E6ԃU?`^F>0h+c&ۛ@AQA "@@ݒ^Ӡh ;h) 7\¢WIp 8w*8basv:̢-5`IkuB0ҺhG~iynm >|p|NŮ^xaU3)>س9>"l+b:] XGZ3XbQ FAvɎGG8\Ara m9}j77=\<n&rifjYn(Q"@{<:NP1#p#<$K*Fo~f/X]9MR? 0A2x64) ~߬)Z7J'I޺,a6W~ۓ d-Թjlv#0ЩȘ2L!_G p\G'z'vlNe _rD, \"@*%&sN{qZ#5c珳-cą6/o/cbI큷6b ? 1?qk_dFM$C?(,TPrո[@ 5:s )k$틦+y^{fuvz8Ď| oFr2O, D"@!\^anQj9c-01*MӊTeL#T!f/[$Ǔ'sAuzju| 9K,)?j<A[=s<\r0YY DTJ\,.#ڵ9Bm~Ip ܀jz,.vcxG$ jڵA{kwnYhUA=`8h>_].B)1y4`E%DŽ}3_ha=55Orsd}}ǹ[]MU;daԎ%I"D h1k o<Bɞe?z<Ù܇}I. y  A67+Q+2=ZB Ow 4{ NyþPmupXoIЄVdQ8Q,̾$ ĤXwG9 VN \좦!!K`}Ch۶}Χg]˒?^sۛwY`¦~{\i+UU T s?wR7uL>`%D"P#u=ԨGވ FKP1dat荧e7JsVqHκ>a,dvՆ, MA?nuM,4? Dv$@F;UZ D&@Fԃ%bԃ*$DdaC"\ X$ҋ9`E`TPݐQ7$"Q^ckDzy9.[ᔔc VF!oyh{F"!\fjg_oq%r*r$B/uU$lC>%iY,| <B ;nj ?/`XbNCkkL7kv,v"`0I|Lu'6GLTP xv묤^ZR3C 3Zl긑c-x4~daC"@ £#}oq$xvUͤx #ZZ\+i K 6#e\[;oX6jAc8-j %_!X;Ʌ,9,|QRQ&+ЍX#A"@@Rzg18ڈ숇]C _7{E_0(Je\ԏ<( MrC\7+Iʮ;$zy'dXmqGޤ(q. +hmO&5:H.LG4> ;"c[Lc+ Vݪd8<1,ʹH"@Ig2D!5T4ۿ4nbIomE~hNjq?u=>OTDA2²Ѳ&sjyP ЭzԌjJs/݋鰞dat "P7G8f? rz>~yf$ :<R2FBhsi­y.W}4 (^.0h\OmMDFD0-n4t=j)fJqԇ,2Qw"@@!P׋Un!:b*F{؛>xG<` cp$:tkwnY{ULڠ/_N.? h3%&&8Ĝ@ f@hZ$bmrtC,rhQ_"@@`e92\R11$atCnJZ'+<"C82ti mN6qq]ry4⧼UL{|_}W!Ò57`I} ",D4W mۚ~5;N<e%n 57{߁L Փ&lg\yj :׫phC/:f[چrr|vGH"@ɻ]nɩSy#oՏ@Œ¨ $Dz%ND&rf0QMAFSZ Dl8ŜZ V$I D"#@} D LI" D"@},H l?Jy;B.OYYQ.1ˆЖM)-@n\m*i UOgFI9+S90,&+ I0Ad"Y< RWjt,<G,T%[^Rꎝɠ(AkG;H<էs 2XERQa^o-ecn 磂%HR $pf~هi D.<PRt |Bb%;u'%I̘]d ?5ey8Ƕ:7r 35aI0ZRda "8|pYjF%0X؁Ѳ{:'82*8C <FC{G),8 \cT"2"p\d 7LVWUL rc/Ls]LnKZ*ԕՇYJR ¼+̿:>eĕE}?SG=,S,<ah&eNOwhf5`8e?HSR!u%/9XFDlVІenԵst]̛bZԺNON,# ü7iOfIP6Kh/VYؼK<VVgX +:%X,qr G $)siM+ŅHr$Ȱy98 Sc(v3vD:{<qR:TGށb']vf Xp0D70 3GF̑r?V%x{4PGw#; ofda4!݈pKȑ#<ȅ^v_nGߞ#<O.bVnt9E]%dBwnK`%Rl-d275q3Ha9)?Rٱos$ ?~"ٳ|mVI00vL7fZt.($C!^2nXo=2䋈 UTO2,a);Z]t1N"JjWXkT6#j6Dۄ>D G`}㗵slۺxkv>xqKM7]wN[U57$y2ͺD! ]>h2Yo4{ȇQ.1O`e0xV_V7QT՜hBZ"@hGg.Ys2F@k#G+< --H[$a ij"@@y#%a1T0Qԛ&@kTԑ"@pM, ר# D"YQQG"@ D50\D5_BLPOH!驾`鼳Tua7/`,X/S'fEL:PaM/Hc%`㌢>!YLg\'$1h gf'p3gѲg00Oƃ;y%]:_^Ÿ'+ 4`2vtF|R/у,9(3Ian$Yw#F*jLUpNMTYD7x^(fdlӊ sǂC;Z:|}`s Jp(s97ĉU>v3˅>׻=7$ zCI~B;]-N,> #wbF|> /yL!p|Aww?Qω@6`B XX<XSHX@z:ۦA]z͎RC޷?˩PX΋% 7]ܦLFSR "PȀ׃|Xh`wH4}po~w%iT{qjc'`0~R* [NΥ/G_Z=`ۺ JoD?[4d@i/_u{%?OW O@ \|ůЮ]vb~y3P,] @ETƜ^E9ѾOs(ȃ2`=̽̅_O&'X`W+߅&5W8 ]6cݽT6 j40M#D ;vlӦMYI@X8ݔ=PɊ =j׀M93i?D8kb3s/wʙZhRJ{sd(5~I9K1V2/y{[rԿ¨TI@k(a^p.z0#.p3-9–Ot&y ( Hb4p9`OqR'fMj= kRv)M<)c*_[Z᷀ D)\pżz3@seL1Dw,`h<Ur!v8Oİeec+/ixx>֍bjp뤄&Eq|0@\]L겞ULێdX_~m[7oΧ?n馱^ske[Hy7/f[ @5Sr9(:273\m7]2f1ՇUC|УD&4/0v r<q#ya1m8,dl4iQ+$"P3ځvht psHH,׺NAF, n hE4#߭ԏA "@ D¨=SH DA"@ D¨=SH@3g0`%0Ze*+r$X JZ15Q0xᴼ`êPHUմ5ДsUA4 MH-- <E UI@0? %JoUzcqqT}^bd d!`\yǖ)ޖS :rQlİD\ZRv¨KD`͍BUQC95z nf?&j8_v9n$CAo(UmnT]¨$D &v?lh]1<O%^ 5] Q\yD,p$g,a' -$yʤd.i(yqJv jubkH=[Y-wHa"@jC &fYB%P^}L/E a˭ԡE!rHG!mj<f.b3qL)"lu:A8ʍtKrP<e8*[٢,[&Q8ߌhƻB:"gӗkgrw},e$@# (`<&s(gѮ@Q!!~X8?.gLxZj:ZΠ{y$k53i0E!De!6'XJ` l'}$3-29QM+ y%g{IB y iF@} >4y?S( F׃#|W `^F'_Y" Ĉcs"d/caH%z~#vɠ:zkd4-0֐bDԗl?aQl'yc*xBnCiŵt),D IL +ηzz rA\"ccQY<$w]2t&[oUzknu"4 %D2mft-=74knwy{eZѨV$ Y:E"l Q&m a43Bhq ?j1N-u"@FX"@@sG,^tF'&Z\e ld4"@(I, D"P60FF D(:"@ e ld4&ʈA G^ͶY1uEsu֫kXZoJ)B2ja:je*WS l6Om Q[$ a@( W -kvp[^RnEd& C>EcZ,l%UQo9\V!̣V2,D*CQH8 tvٺh{G"P@8~Jc_-ٱU;H<$+39-lŃ xk"N9fr'è M6UogMF1җR8|p^ 4@ߝZFT#@`DhCbTeTfq&<&?]ޟnѦY,wɢ2jCzX*SLt!1 4G[/%*[oPgda0'DyqWvu}lQ^n(fII*q?T6 ^BSF=,q$ OB Fgp"˻ڷ|1_Zd!/N?,zgq % b[$ $D5üWmO%KvZU>i`P 8ctzk aUfz/[5+bp KcUmGP < -CA tu0:ӊ@po^)ѼXQvَQSV@U"8!}RoaV]G"skbh&w1GL bz7cż0Fy{4LP@datM%6$pȑGy /\[[;ͯR> cVY"eZ]Ǚ : 8R(n)ջlTI/€e_DDv&C1}XTaLKoKW 9#={,//=zum~e#K0|)4)BD SD] DZQa\0d9d~X;Ս(v+#{ 9`yCiVihD!_1Y[?Whm[7oΧ?n馱^s0TfC$@xVJS׃0Ad"@6_V7RfR(th !i"@@@$®Q3@6nuJqm4F cӼD"@ڙY|wimD"@6YE%D"hKk#D"Q(4/ -I@=1"7_XU- }SkvBL[JaCUSk0 APA8w4KA8ƒrcd}iOg)MFR&&O2`:QԘd'<5z,43]J#Pe LUM`]O &c/cVKI,".у,9zCÎv;9ֹp_6'=U# =+|< \FФkzv},|)1J1<ȌW_7gIč,q¡69}S# >Dw'^ 4u><|(É>0iE nZ#-p7N1DU!9(r"/(;ČULQoPԛZA)7^˵r\ u(D, l"@\\eh.Th% zDROLOc\XX"fx-+PkZE郻M鈟[#(b;n񾔩Rq0Қ疯cPKt<r7;,Ր_}Q?v 57F!(!Q<_`^dybr^ObW6W3f:/Clw/-ѵX4; Cc"&1n, 5_6!32PxZ&&'D2P!ǹ/G+j>ENsd1qnў+}dS0ʀE]d9"nKtE#]|,G$w&f>VI`DŽ%(VqײCZ!U؜M<7c옭~,:`YnԢ>$@F-i,"@ڛ+QŔOwmÐ0#vI9 >9e!Ϩ,d6F5ALAU VOjWEB8'1js\szD $kv.&J`}cik -s[[zni,x}vu?c${O ^FqsC<{ yMőa6ڹrvI>Z%yD%wl Ÿ'tYDYB ccDv X\UKh]Œjہv,VS' K?_7ڼH$@FGvZ4 D: ΀I< D$@FGvZ4 D: ΀I< B@UIC2Ҽ[uUsJ b.~,F4 }Sʔ")P{ :Xj40J3D@4e<a1;PATn8HS9YQ@>Sb 2 aD- u0:vb(A ?%1u`͋j}I<$+39-ݴ0[ЎFN3eFEXhy=}Z[;0ZDԐ.W)F0R \#>S J,P#hr ʨLy$M~޻Pɛ\k?b=+(?a3&̗fj9$&¨ FB@W\f%5=c:E υҽ`jPP*T~iS!+)Cٌ38]7`LFYe(łz,0fJg%MO,E  '`\"$ qIɏ MzY>M'fvYeiEp/2/1]Q R:½li0H1\]F,\"@lܛ0Tdz +n?K**0\1Iw ga෰w+n0z,v36+ B$xB2F9=dX#0hf @F3ҁ #pȑGy /\[[;ͯTYa), -LS`)YT/Rl'" ys Hꌩ0NVpE a7K@>={,//=zumM0,ka@ػNsz& aqNh my Ukuu8z,,y2Q@bm";Nm1+fӉ tXpu-uGBe6H"I'glV4uc1i"@@ esj%l31GRj+590zD ){pSjK-H,i2 D'@F"R"@@  oL D $D"ЂhF*"К V+V8r&kAŵ\)v<Kb9%Zs%W7*Rp嬀60f*D18A<ft:Z5TET2H52IEM(<Sp#t7gX QV5aBB* @Fh DJ<E3`osaN(ëB("cl VY DTK@N+"'T@d,VxA$F,p:_ @C_ȂhB"$PԂ҇f"Z,jAv|75VLC,pYh[Fib+h v1 6o*eJ|x _sA8^||N3)!l Ǜg_-`BBa6HP ʝ@@ LI;EYd{SL[4P ¨-OF@gpY]H<?86 dk(r\ςq<f_Eg"He NRj0_Ne6Ir6P@NfoN^[6Yc(iP0ʡE} &. ^>ZROHf\(B,DyV%WY[*cw5//*7ɩ<ĘG[`&z$@F 4R& pȑGy /\[[;ͯJ-e' ʝX7M$pLd"wriCWpD$XxQֽpҀEp5 њ&D` ٳgyyѣ?ԯnQ)Ȝ"Pb$L8 }!a> 0eq/+^̱7LٛzL$؈?5:Q<g-谩f:Sh"@W k aٶu|:㖞n 57{߁8`27$0`9n),ofLfl֭ӄ$WL|Dvq٭~Y-7Qs,TaSII`m Q[$"PcIo )$eA%BƥQ㥚~=52A8S߱6\x4 ҷ'D"ФhCj"@hida# D4)0ƐZD=_qJ(QVg^ɱVp1ET8cTeȩՆBqsܴu(>jeJ3~@Q7uX0:vbh"8sLIY<vU{IՒ;~L-/U +x͞/IO6@7}InZl ^V.*G?OUF_̰@U3GЙhD /#cT^Q֊5ԉb2[;F21<J׆&(sGF+ DS8E؂؁Ѳ{:l~7<3d( k%=@`\Na!# # #J4LQ[ΕK[d(N8f4rZg$YsHS"@ڑK#BAhː3uNB)I,f#2ЌnlFX3챌PCJRIznpt~ g F$~(fI*PEHL$O.JAŸ[iZA 0Z.D5/_/D42ccwr*X8\+B[a ~lh?]^u8@ãztyNEڂ,Ork\LrG, w D>;i&SHHEjdI.|c]vsT0E 8`Ҧb 0;>үʦ=Ѥ3P1Hu=VA@K(i^X>sݸ'r0"ްwsOv 2` S!H!pT^XL\o ˝7-[N' ΀I< D .$9pd!LۀL7fZޭd) Pc *,{dL5_H="*@6i[Lkm X[?Wh1۶n6ޚO'3pMc{;pם67߼袋Z|Շø憤0SfY<ߢHYuy4i!hE"V:aSge/~( {b*[KG" n7-" ځlVQ}dʄ5 -,fxNjz"@Lq ,!7Pf&@F3ҍ"@@ UM D wt#D"Ъh;Gz"Ο?r SQ\v.M@+Q̍p*sg,iIJe#꫉=#Lfjt#V_&GeJ.<Jhbi18rnpˌnn4o>damE"8tLcZJD~UTdv8[ɲe~he͵ē@ ? &UuI˒T m3 T\[!+O6218(gX Q[V&LFR#o)1XMök(oVL8R?HLq~VM+(6(3=0#&C,2栿9xu"JJˆ&+*Zts " iC@G(Y]T J:>"0gZxYcAS8ʠSzׂ%ņMQH<@ cpݴP!<3d( cq|U?YɁQէ-JN& eo)N@[(ad@y0g82ؼ@HbU^@U F紧" " |caPLI[@%E XR:Ba6HJV) pV" KC-B!L8x e z 泀ʄj+ D".^wEFzZ8 B/~!0Y>cb,kUUמ|sӻ K >E~0%1ahA$IJgAg,T%5hUw.3CvW݉Ҁ2,2xsrרr[q$YxHg"@ڇ@"9 W: <!I4F}H*b, =ab` MKH3%M,  SKp\qޡj3HQy1o&Z6{,6"@Z@$Y<0.KyJ 8&y2M%luFLKχG| HuW\r ^4kFW|-]BkFܒs+[r`[v -o+- plڴ2'|&ǃXycaC~yuW*,а4AFY&0.G o.G&:kd!LY87.K `2"z7ۼy~ ܖX()IZ+k -b[[zni,x}֤&Z曍)D$S6ebJzx"E) Z>Y3TV616vhAj"qc^&ĞθZ*c8!fVe cYJ2 O@;P5-%? ҄ QQ$">?n3ÿoo h@Z"@h/da"@hda4} - D0~jh>*# yGƾӕǪ'FI?bj,`!&aO߼sj4 p dZ&jkBa(c-gD*&meɀSw@@0?KǗKF [uxXTe&T}шI/窮LPLNZމ 2C`lbs#ǰo&i'8E=WJ  D zPm|jv4K\!~č,q¡h+9\avVeF zC"'ÖS,e0 -L80HecF hyr?KPXbEDXrvq83G(,sC`VtoV2/y{i6͡u7VnsMsx-2ˤ^ˀ" iP%¨!DT@ C}e Q`7&x>~B|qOֆ`"량q}\9QH`z۬2+D郻M鈟#nT-RŸ?}D|r 2=1}Ŷqeyӝ;u~lc{$aQ{$5{ggB $F^K`2H@;CNfg[p+~yE|6 3?M[U,"YY@sνWuj`aj  0*en\~2&HpF FR{:9G)K<*ErU 9ZUTP2"zq@XL$`aSz#y,F+Rd=ZdrJ 0/̑sĤ;rPgAnG`b(ÐE_`ag  0O޼υP0zpd8 : (!uGgy۸[bm嘆޿n4Pĝ]r6#\ml六F1t&|9SOm,܁0m3^,Tɀ1UˉɀL2ze:( a濹G$Tv^,}..OE'dYbghP: U].y)݈q21{E6e2?W7:zR-_2#p;6GCNN1z|$W {/~ai77?xwP-th^q&z$ŭ3)>\vL@N@>0L9Q-ֈxQaazc  pjq j;?ԛgقA]XX&(   ># g uA@@`ab$, -/^,Nq`v .3.V!j4H6 { s5CG{KtFd=p rn 4M&^%M/'Oz.v·9C_LˬɒYyĵ@AZfi?z/S38'vUv˖B +J$֥r-"85D/ !\gϞ=x𠋑!*vʨZ0Q$lKs >h!ʏٛخ.DP͵Pt j00^ SHڵk݌'{ŇFӏ%=䑸]樊vh#N[1q d$rK2H)Ktȱ:4tЂrv=h#`&ii[o+h0Ћc -=!s'UTerd!.r~6TC,x9bky+q'ʕ ;!q}+^}vWRи *N堧!<OHbLV2H?5+USN =& c`t 0Ξ=SuoQN99(.~\x&%[,FoJ((SmD\0k/$/8ԜB-Jb] 3;I]\g}ZCp{ qb1Y˜UN "pΝsA.^JWL|\Q⥬+eez\En^PJ駌zƔ`S{l[ReXxdφ Ҽ _rJ*Y~ ]ZtN#tIX` C0@`t3/xuJ!uCۚ 8si&}Jژ_;Y!X#6Ը䏎] ]G%ñ%[s\*J ^Q8)|9SOmαJv9qp=0]YSNd`aL@5S$pGF`1',PdՖ~}d ^\;Cdv|Sis]ad[!vm4A:V\n+nD=u1N!_H^Wd  P78 SLcv'_;W {/~ai77?xwߙbtN篼J^hUeGRtkcac :C? HBlu#2ce1O R+l~t7LH,@70|xOL!@@@ )$L2fSMTS)?T77^ߒܧTY(^FCƉOai[]mwOI^6`aLb^ d0 V".NXR[t']7 mXlCw6"fj(6jYɲX5,! cz  0R'|[9b&e CEͶDӝUq&6شiJT -)&y3͒7aa`i!X. y_ʕ,gl07&gF1 sIhq WFbOc1<첛g*2"Kͳp<" # 0y:`2/m7/(dR+M2+u?TTޤңm-AzYC+fK`U2B2;F*f  ;y߻]/=f[ECZ X,iQ\fpl~KQ p[jMuVP%mZ`[Sdta WFY% cVW#޼hMb aaC z *%i t5IdЕ(Ռ-0m+b2@10:t _~K/?+sbaV$`;'HanYb@6V)mh˞ع+\,vYx'v$C֜PBy~nD, O0B ZGzaYη-)![gJo)Ł'=e)|"wTٔ<.Å K{XP$"cy[SR; ㈕CýpOP 9ƞ o '_;qWJk}޻DOPXTm˾ Jq혱A|SXHǡm*C9`ac "@!\v(ca6Ď  X3Ԙ("XC13K)q1 X3Ԙ(@W/^pCy/Hgio#9M#5&d&ys~%BǃM$SQ\&Օ@S<;s'=ӔkAz(nIFODh 0vvv<y}S>dj3TؽGﳰ&3|!_C^PojFzguXr[8&鳳kc+9kWZBHZӢ I=!  {Ϟ={A#y=J 772MO  +!Vs&5aƣ85ώ_m:JΥ-)/I\ %Kw\& c+A&k׺Oѫ&u/^h$cX#CZ=-b=-<<r-ɎGn_zլ#";}kfBn:ٴsT}rQ~Ts{+0\aB#!xTY=Vȩ `cO/:K} (V)LSVS5y+ <BwRBѭtX'9-rn,뢉fu#fl (4n#Jho~IA>Ryf5k}`a6gϞ}=WWxAtf&S\J.̎' t,_>iLDWV@Dp!0-KH^-)iߊ;cuL70-=Eb,d8K3vȍRJ;H_NBݔeBG\1C#X~X% pZܹsܹ`0h3 woz9ߦw^&^r·0" X,o#RniFd8\}&Ln/f``1Wp!Grنڞj 7zIƐ@`zt3/djZ<f8YxOAt ؘ׃#(SDZ)l6.ͤDKꎑVm-R95VwtN1vv:k#eҦilYtE+O '3g3eTD6Dcg-~=C~@)'#'i҃)<oC۫jvF%)ڟIC&\%U>󱸞@bg0vz_ٹ5x\aw#I |UP~ -ĂNN1|$W {/~ai77?xw@iW^yepF"i &ow6{e,&C1c{JcJӚuu"=?ySl4GZ9cA>h7:>0,Y0_rf3hMRn^7KF@ED- HH,ѡ##Xx8@@@' { 0M5PdfH] G 7Tlu ͭ:m%UV2OhS[VcûK&n?Ilw^O}V˜<g0Fܙ:?E>TltHɁy尩l1%VRjHUn9)ݿj]F) 5^R]oLjhj(dvFr^gp!cGU:]BdYh/+)l;f  `O J}'>saƏ OX֡f˰pt䭎I5JzS3Erf%o+d-t/f 2/~_ .K:wsO9䵯ws |z)tiLУl6 3% \U#@v~۩yF2 FXIQ>R׫,fӼZfWLe] <` },>&c1" + oҼO~}D leߧ8&+/b5UfWC~57,VKp!͇.?uUK:B%ѱV"M#FjI-sM@U_f?L?P!gr63*H`;Z9v1iE,:yPHua!:l7rd.-bk\sX-s,TfG% 0\@Bi'`< o*HJ]JX[HYUewk FQ"J*~:5oo`.:FW&c5QUC3U4kکh#g$P9uЪ'#HOjnjb*@E㬸-("@հ Cy^e銷d&Yfp9~Ζ$Jmn#|Tz.Kw2gT1Te%ܤ ԭe 2X(j0$Ь61+y_~K/?{0<F7n,4jGsY:+HEhCݷۊd%u䢐m #yB=^7 tq BZ !e9S IjgȺPM\ L+7xV}W_ovy<A?Er#"MbUC~ySڄ:yTNaD k],jȎyErKV fBc/cZ `A%aT碻ҦCO 5ܫ!?}`aO5LBpyG:NH |c<>I_*--ߌ_3}k}gZ4P_Z3 %l-M */}=S->^^L@&@Di9&S6.,)[PL@A@OQ̍[yqyKL i K@2i'3o' OL%T&eŤ@O`ai+, ?Ղ ~$ `0:)ȂdNEmu00*Z4TҵmQ&bKt\[4rJo9-d:9aaLZ@hKyiz+XICJ]^|EL-*Jǩ*ի:MF箆EuV.$y%Ke̍뤈1)+=@|M|'׊e3it,B̖n3Q3IaRйc䀲fɛ8  B@N멍c ~lT@yҗKB664rqDf)p?SZ&_W{5ݴD ("x@s\,1e7JvaN׫,fd"g6(nX ., <  04K)*/r5*?c͍ (N`y54N{GE <n5YXaQ&U5kbWT]F}Yj^)VPX1BJYS1AQM+klSG֯=Qs\,&ȷ_t&G KK1Y^2U+jXX3.4Pji<Ź [a7V*LJtU%^z9 Y)LVhoD$1 ya( 3UqT!%߾Rsi(\e~MU,jd5(Yc4AI-p=%5 zYW[Ԙ"/|5qI@|An2 `^tEoq*J?UQޓ|˼v||Ăau TҲ#s,"A?GL,'y!V*Z.+^ެo =<;$ b˜" "_~/cq  ͢ ;c\g̱XX G7GNWF"M#R: W|ڔҎ ڈQi[-Ps*zZИF9gS}Wd 4/vOKɐkF.Xx@@`oFVꫯQ~Ak|HK౉: 5Ȁ̊hez> T: E"3e+zmPHY^rSBU(SĒ Ǣ J8q~9pn1jiO~h_|z89ƘNpU^`if;Δ<% , DT&ZAd G&D`n*c  pj" hsjDS,39˜&  n )[v wa`wf,XfL@' _"~.p `ad   3G-9&   @)@   0s`aܒc³AzN:H(6.GKɯiHGNۀ#v?ɪ nS=Fڔ2sKftm[k! T%M0QtYhP!ݳ  0\pq$Q-2qr-@|oO2x2#RCâ(RWRBu51EE :UlR[9GU/jӘrV,Vh cx1JM>ƹ%꩎ v(H©rz#֮) !hS֡fRi:U֨1?0Tr#Ho(E+ Mǐ5A83*ZfZ$R<h"mZ :covS\;yȒ-,],Ct<jʁ l$(,"#AkZ_C?[iK3yF<#G [39lddze$˜ \,Azzw8=00'?0J:)|#-mf+#uen"P{A]Z!džx"k,k16 OүNr* Zָ\˞"O概XnG :X5Ό.iSLâR JV~ٗިXl !3ڮ#PG*"+Q cuUu8s,vEG2`ҫa]*蔖vQ2;,^=[:L! {jFErj~!P-PDr5ÕZ̓,޲ҷr4 W;to(JZݱjH??%z+瀛t%Qf*fPӶs..F4`ʴH+}{>!˒#2[email protected] jE^I=X= @@c. cTz 2,;mt}w^%U\YۡspФ\*uqǢXNjEPI嵨AxdYYfKэ^=34y[.+ezlС+ܙߒ(Uwry~@< _~/cq9 ]y.ᅾG6}Y7Z_D!C;H\t鮖U硹- n>LXDm +lwvRgJM, *4] \z(:h8o_>Y/"+u5V!!WÚӵbʜIOc0:yf|P{aah x7jW_}oۋ\a 3EQm1P|ߵ7Gy8Nay<2a-$]83]. ,(! {Di{2) `GX,J< L7MD2Đ꜋b\I5+GڦIBgF]NvN3<<@``''}OvsW?k}޻ :N8s\a u~|„:MCLT闿̱eޏ|E{u2 (a8i c\kqA@@-=b'Te5;w)B$ìC  LbN /0^@@A? ZAŋi3 3dcs٭~a2]_TР`]j*$x=5='2WʁUI ?c{rc0oݲ~Waab$<ydD<o[D^K2t -o_mJ*?APvۚs֢Y^pfcȍe~hӐl57 `K`<{`d8A4&t,Ts~fZŸU UclZՎ#:^9=.t(F'mCaay;vK#C8(L/W2n 殠2'HNPv>jݤ(a+0cT]\t߲"m)}Mgr{F{ 2G:WYvͦ:^fzNrZjX^0fv1qpcdpC!Ȩ( h^XޤZ<@PjKVE鬒ZNR@VEyqh4IqXY9k; FD"o)VPI>X kZIcVkϺ^g1YC*E9WǫwʙB`yXYNYTk˜@ٳg>}m,>'%MQUM@F}Wxr[k{g:a%k@HRi7i+S&&aR|k5J]dFjrrTEjE^s~k o+}A@@sιs`<(3|rQ &IJ Um -p 9Tj,8YNZTi\V#rT]TTfWyq?wł  pk^_MFߚnVpDtMxsXNcE=Djn`Z,qk+G+h.6F*LjfD#>`ac $p lN ߬S?*,ohL\ BhG!#cA/;F_cuWQps$FQځ=wE|.2B*ßao #'IDAT)g3]{B +oOvW {ooiW/67?xw0?+ yz/Q52gst$x62c~2F|aLACh#Qc?6$C֬|aac  0$׬[p=ʟ:AyP0&ta, _/ % cBj Ay!l'tYs[c?%;C,m?MID Nd->!&oU+"K(t94k' =+gj3T` 鷺VXMP3%Ժ\x)wwtA@WNu%nl>^Ѻqc+hstTh zO0&pQxF X~ ٵ< AM5Ne=ڮ)Vq޼A&ƛxϦ8Eףf9ks-,RdXx @` CIbJ \\߽;'`I$ѩH>PNn~^摵`𑴄xs I[?NgӦ%y5jOq%|As] EBQMbpyEW$!@&'OI:St֓lN$Vm'hJG Lf؇BuB(V|{? YXDj:iTs{Ghs(êtI_IƤQ' GqүO\ܫ EQ}7Ӽgy7i%\2jF/֋J0 ,oV"X^vW'49D_/VDP54AL'Is]Փs.€,ȑ- U21yN%}<"nF _)G`0Ea ^s#҆z"#dǴ"&GՑ @%f GWXk%dh{cwK,mPKA\^)"6J4(s*3v:KY;‘C)"U1,(,r0m3CggX\7h  'X$R 2!T>i ϙf te[=tdEpF;cc[ )G/$tG[6(F|a !zY`%prN^8Ua7_܌_3}grgͦƲ X/U^g1Veip0i51|$< L^NJ= !0 l?d:D^dHX>Y(   " WeA@@'`ad&, _-ᓅ  xEwͦ" '4%os_%t>r@B5 ILs8m G%[uѯ]<˰0fd1M! læ5OG(tNUl*M7#+ʭi9dzn/.UM: TC8\JjSUP^rV,V8 ڂ{كNpb=ڱ4V=P5kA,gTSFl 7r{eP4K< j{1ɫ@@k\2A[-QM/z<LIpn6FV`"r@:oY_P""t&0\>"$j1FsWXJRn6fQR8u@ BJ`FXTK,U$;`J!5ScƛuppXYQ_; F>B2 j4G\aM+i *ߓFȱb"=PN9:I2^Q1BevF1kL;g>},f7K~nSOJL5D{憨›s[k+8Bl;HG^B!㚨C+ܫKjD1B!VzEj%c!'ƾCcX~X% ܹsܹ`08p9L˕ -p(aHf}jBWȈ9b҇j?Ž#䰉wf̮3{˜٥A|Ly!|7qK0Z(S 59b0ʱbٝ"rGfM*x'J$#gYf?mK>c"cD3" _0fx1i&@t4vv l9PBܺo)L"O`*$e@fzv'RB_ ]4 R|a0ˬv,Ed %ЎVnIF7&y:Оջ"CO!Jou%͸~lC&۬oA!pr1㓯&~WYZ_fG;CrfW^yef\ Xirk[e&#|@P@`^ty&"JssK=|6X2\:E<wD˜>  JIA{ׇommN$ۊA_X~X%  ~# o+}A@@`aa#, 7pJn *`p)f'Sɲd.ws'IڋCy16Q̸)O79M,$D.IdDب-Y cWs'7ّ SiYJtաn.dT~n5^R]x0,^+tʅqer#I8<EUbI!<ptX„(gT`o1c7bCSo*kYxo(}@od81LQ'i(Q~yZLۀ0mE1Y]sk2P:O Zkc_ko#@`$[ ynf)N#h${]2Uh5` a8R׫,KTʔT4>z&YUX: $4[#J1F%:ȑLE+ <všAF6(0D)VPjIb%TzѿIչ(*@VE3fC|knUqˤFpeTUDx5T]U2I)nI:j%%@LٳO>UBHnbmn|5<om%1 Din%hYlEѨ(& #F3DRO|[qXUYUC.ЛMbT#0< 1  0.ue*b9XC0>FݩJ62*"JAniJ1yEZ(JTj2T-+.X@ ;`0| dl}ۿ)nO%J? qbNݛA@7*, &)5Rk"%KD觮j]\ S^'fZ,^~L@`Μ9sܹ`0. l %ݶ5̖%UP+ʫxlI;#M.&F08dœ)+3*+IF7:{$= h"wRⰒ4 \_Gjv-  Ђ eZ-H |c?>i _5*Ugi_nƯo~{3R!;ϟ{[di5 {KLN<sc&_4/+=A9>G3@Gl/0/% [BU'd!F<R)"c#ׯzJ2WjN2u$'stX. @\00v @``a1F# c31z@@f,[s@S/^)y/H'N[rF@R|i۾~4Yڳ/1p "!hfp41A_}91)%\Y;M粢Aw0Pvvv<yE˟RVm u?ܺ4VT̬fKf8x)wfDa?([EUitY8 y7om wr]cݛn,ެ1+yxDٳg<fd<_μ&CakqVGs:U1M5NF0)BiB_؛trZNxbK\ %KO cZW8==*_&׿h)wLk|7&~G[C~<o5i{Z{p-ؑoADqV tvqeڣr2֬/.պD^, <  .FF ͑+>2cuҌrrrV< ۷7ͩ􎼕2[(IK iLer8j;DuMxV:hĪnF.pgW-rw*}^f9!AzpCN\ѼXx>@@gϞ},́_ :<U*%|/˄pfcW"G3,߬߬R3y<+>ކKGR&zpF;0Yx1 2qtff'4izbX0 $̾=X_x7OĬK1O u/ߗ!Ī':ʸ 붑5CW $<˿N %,?Jӷ5 9|BdQa)9tINh0vi11S#ݼhۖa r+/3r˳S͋k ib Lh Mno{=۸[b-a X1I\^ZBaL=9v[grPz'iTܞ<=XY%8s̹s#WF0yD[@yfƇv(){RCF>OȚwݻA:V^hi+<>S"ODž0WNN1|W {wEK5͏>yw\)F] <:Sg&v6ch,lC6ƢĔ Ɣ., pZ`^ J:Im{TPXI`a8mZjňO)u3+~/3mLnm`ay0<L%XS,1/ ng4@*8G@@@{0g ~$ 7j9tdz4Nh0W2٫gVM;r\諽0m +)y/Z?%,mlgS1M)^ŭ'74, aB t._vڷIC_Lڨ[as6dEB'R854?RBZ`}/>F6]y]*e `z=3JH )^ gϞ=x𠋑!{Z/QgdKgoV-m!gr.ÿUeiЕ*]EOBɒk`ay0<R+)N99ZxPH79jc#h_?E"$c ~xbMvjh|;%H^BNHRaŽ'<kwc:BQ}]T@ L9FFX<>wrp=/.jmths矲R\TTWrH+q'%j}A׼rz/ŲPkո0R>qV|P+lĊ+.rʛ7j,zXIMƸW`0PϞ=S{ _]`(i`^6=Y^~a|j-"qN›c+cV,7Ya\ ,+QHI]L(bHp& ,\h 0갋HL|D_RVW͇voVmd)S l=lד+W&ItыI^eM -'@4 -0+_<OS3A諔)`~gmHy/\lOet+Nb ycwKL*ۓ 6[Z]e<T5n0ƽ@`29sܹs`:ŜHPd£ekOʗ~}d s  Q\Ca1Z7:ʈ_ad!cD҅kAu*V `+vJNX$iVxl A+ek(hx 0#NN1fz|Ӭ/W/Wf;Ό`t3ϟPmxfhb7<sq4uay5C>~h-y1#$  !]! cz   !1^|[obu:`t, <   =SHg@@@{0g   0 @:u9<_ )nvk*]Kv*66".~&ʚqDE%i&=p rzj ',ZhɒNk HoUBZK|u*]Ԅ|5rLi)Y\ϮItfz i߼Mg_.o^!iVC%f3EפBZ.:֢%EH>hhj.-QYM\/RLr-s^ u-, Xd穜,,\VL f/59grr,樊Cjc#h_e/d"[2g~È ́nbMvjh|;ıiZ$eO;H4aŽ'<WN!b?MP{RJ>u3$, -hZNrڋb"<"ke?$hC@DL%W qQ_ʅtBwR$ST{.ZƭtUG%\7݇r_a#V|_Z캨½AŘ#\%s@K޻ }G (4'P2"@?DI ozƇ IXfJ:/jZ{ ghUrE 9))mx?e7yBqv1'/{ qg~5G`a AJ@T03L|MD⥬+j=pT zCo#Ktp9퍍2.ú#[#mƽ"[\GW7(K^UI%ˏ-7A9d%irUX&@4"3H@d_ƻ[745~pf~glG:(rD["oAet+[MHw8cwKL!*ۓ6| ^RD(6坈O@1GÑ s㉥# c3i!X̉ EX*YfJ$_}C['[Ov Hd:_ad!Nv~jBqknHl  b䀫HEҟ&a7v1!_H΍ W׬Uf HC㓯4pU^?j3~|w{ 2T MFsܢRԐE:҆>!O j@Vjݼmz&/ފ4ᗕ  _xjEpv7Ji4F0qU1'7a{0>t%0y,r 7&W7h ab$, -_e 0hkw}o{]Nm^}tdj}ԦvUH2Sni%囅[vr4IM~6?Zfmj9؏4]@  _uqIߨW}/HzgF.X<xyka?\ ~RQ-%  XL̅ϑyѺ4~}ώ-܋CmQNg,XfLD&Hgk?ͰG7Y՟F[˱?!Mpozn09'"#', XcHtx> mhEqMw{.GLpG/W<&P~ko0 sl5; Xb:ZiNrŐ&Ŋ;inl$󃅗W=Z4F^W{Qw'#|y+P1_+.i =aȞB~G*-s1Ej\we#u :)܅o&RI~b"?!8Fܤ4r~x謹) @X{Г$Z).aE'd w\J9 ]h>Afw߷2Ffϛi^JԊYKZIKڿĭ?V1;NdC)V LB><&ߚI?K8>Nѧ2%F%Hkٹts.oI/p΍}?8C7ͬ1++y p}DQMcCv|voE|w fҦ!c!~zwE-0ݷ{21|--B12Klu#kE'w 0v$ (og% (Gi2/rJP!"[;kxϊ0A:lō4irk1+CDrS4=}^.\ 0 % V-E'כk}޻|]@]{_wh^ ^g?V ꒌe iP0i51 J"4xqhޙ2 >aYd , .T.|2S4?ɴ,S C, _. '< _ 7(taObƬ.SM>^^L@@DƘcXj0zy19XcaA@@` ˜@@@`L`a <& c11&@@,^^L@@DƘcX->-_HIFODh   7X}#C`aD   }72tIFODh   7X}#C`aD   }72tIFODh   7X}#C`aD C84܇A`˜t@@@`"˜e   0e`aLقb:   0`aL2@ 20lA1@``a} L!XSg@``a} L!}\4S4IENDB`PK!0C)word/theme/theme1.xmlYKoGWwŎ -Pqwf UpT*z(Ro=Tm@~T- zcTߏ/^3tD<iyUM–w;!p`&Dz?"R Dn)nU*҇e,$7" "ߘUz%4Pc`{c8>A}۞22J >5( 6CNd tY9?C K-j>^eb bj mg>9]NNkl^-Sn ~},t)cZ{ʳʆ;faKvi (6NP6l.t-e|zPh2Z@x) Cή8ߘ& U)eWFe;\`Md}up<kxN˅%- I_TS 1x㋧ɽ''~9+8 TϿWn,~ Te೯ѳo>2Oc"urx 9x=~ib' %Nq*'ѱpmb{^߱>XQj[=Y MWI.eG.ٝv)4-mhD,5$! =>"AvR˯{\B)jctIl]1eRmfjsbKl$Tf.Yn NqkXE.%'·.D:$n@tKݫz3{lHȅ9/#w8uLH E1ʩ+D!8Y[X~umߤ,AXJp'la^1M^ָΝI8 ٷݝl;r|^o.w]<N 9o漬Ͼ%Ϻ9OچM= #פ zh&8 sq.، f$2gJr W 7R hx-/3 ͅv*hM3XUڅ eՌj #& z=  3ӰydH۽hHm65SH[%Heq%;M fQu;W,gj֛qp܂a?[fa|b7؝R-j(2[9Kfכ 퇳1эVbm0rhpH|de6Xqh:UJxU\jv`fW~^ՁY'Z͸J9SgdJ9g̅Z>F:G[*Ѕ҈=# BPZ%/ZWr4[SPpbQ4DBS d_vY-ye>S+9 Guk=MI=ϝ1u',m^x0ѯ*Kөڬc-7W~զpMA 7>oD eK1 @l1Yec,9g ]rqo|dGWWKRȘ?Y|pdh̔4p)L>DCPK!ٴ?Y 0word/settings.xml[nG}`AȪ}!,jq'ْ&D|by9x̓unݺ.ovuz_EYns=}tݾ,Uign7aίvv^vC]?=q{fvn|%3z8l'n1n?Nwwݢ=9g/fXjhWC=tݙR#Lmzu~S?,? ۡ_)h:3m^V+Z)sF@|E`ۡvrz1{vEVI۹ fo,| 4cul4:۰Yatsۮ_6 Cp{<ۛ}U?6-+N+.Yf,H~u~@<' ㌇pl|${ƁJ7Unn~ H x~_zvɏk5|s_rL拉Gy9i֤/û~I47qA\t"Clߏvt^tt>Z}GF8#͸dmm#YiU} C?,CbW`qrί2U\qˋ`Z[N ZQ!tˆIt"V:$Bh1R;8&dLx1bĈԢ(Ild&rDpa\`Ȧjƈ)ت8Y%"LP\i5Ǖ1<$(ndbph6"%ܳl S '<', DRlX:պDpu*JTH kXtPBI7FN7%1Dh%cJh1~ax!"Ԃ,1R`9ԜR9:h!"=X k!a$9AL9F}NfpE ^0bOrMf:ThU@I jAJ[TYLMtFbJ,g<`y,F>IvͱSK '1Ux]IByw!+ rZQyA)k(#C¼2d:N u8C%kP? c9]+zY,X {eDVGeި*X?T7w)ah#8{GBтMrVjÍ s`pPz֡jɵ0B !sd 0(9t# .d1E -'젘§7ꪬjp=EYFけ*ihUF`jJyR`mbpo,r0V\EoQOy Za͙.93\mdqd^8溌{d)]S7pbf /bqLHUVBO! $DtPpkXKfNɪpg* DAD-fIj[N\%huo ڨMTh3/xYGlDs F$[)axG>r q!+s8~"ځF|rUvI,k5ÙvN=e סc 1ڨTDBx) ^:y͌hmBY ʍ[r|,z\zpL u곐D/cHejbU[L-0nz;-La 8Xi #obuH"$\M j?\"1`]AԀax*0` B$aި&0$co&Ic*`?"8ѐH5 GH->s28D >9T;!D™6R>wx?t,7q K'Dsc܈ePǼUji'(`%  QIZ155u杈5\+';8$CdxOC$'3v8c@.#R:pħR1$22)鈳YW|ҘF9K7S %9b.#-$S3A>&Dἐ50dm2EPftzw$D(8węj< [()[,B 7Odo 4Dh-A@iO hR*bez fjb%?%vP\P~8)hrFxX ^{!o$(|WpY [HPgtMXIp|RRhL .bY7x吃:^r\$|VVW*dgiUD!UJUWIچR KZ3 .3!QjXj_EUgjm'13Fu*_x%ͫ=zp__0Rh5q`DIr#{z=OuqFjַC\o_ob9]?#7gjUfq"Xϗnۻ]3ܿ=1e{'Zv?nlϯAzm?v<k ϟA^4?uûכaa5׳.OG/Vx}lǛz|_fpq{/N8`~4qeL>{O˘:1}/c<fƱm;͇٧q_v}۫/ol&V/EGz}om34~8c8`\͗-9=5AC0:3PK!&kyUjKword/webSettings.xml͏:;C;[㏊. =M݈$ixlj~U68ub*mr]3_,Ʃe.nX8~q"GU[iWX]ŶR|qpluJm_NnvJf(i2UmC1uUݏ?$> ~HU<msזuwoںҘvY~SrqPTmzs٥4 d`[ߌb\M޾<\)[, 6.S}y?_R{E'?Wb;̩L8E>͉)]&ezJ̓==Styk   9mpp@ԗ pH`v)8`a` =HZo)A GF8Xpz @Y$aҞ;XpXP>VtIgłP֬p`0;+/,8DlYp Z" Pea!(A.d iV<xK^1D<xHiYhM(/k%L<,?a i<<gjaUy_F&DR^<~x0Jaɯxxxe-M;#Ax+.@C+Vt2d2`*X0Aă[ h?xx&7-yXJT* Cڏq8~Zln?t{{8+&?}PK!hqword/styles.xml]s6~8z{HmYegvlǺdn Y)BGRqܿ%(.ә"v H|u|Y|4p4dQ>>_ iD3G|:/ _Ѫ(6pE$mhO.Y&=Iݼ zCx'q|ptxx20Y\!}횦?hYM^=A{bYXH:Qxkx q-oI(.>>1X=,#k$`#KM\n3SYZkq|[ 㽽HxPyLZOg¼0_Q<:-Hr>::*\Ԏ%$}(;'ơ=݅<75nw%ސ0eAeqbh C>?~ ݒmt#@[sw>'G-~,fٙ>xG8hj\ǜF?ͥ!ۦl, ɣ!gS"8 q65.[5m+JDM}đȍm6]^jhR M_jH:K44{N_! %ӈ~Vp,ވƱ8Khq,Ʊ:bh"p ڬ0ڻqn7#?n`UVYZ %cE p4r,Yͼܤ@<-$~ N> 2XیC;NO4em@yh,q.iFӐ4l z67M#+ʠyN{05 36kx7q>\W$& Iᵁ^Hᕁ^RF)Ia͓ޔ}қF7Iom"!:&.~H O7z4%yfYvX\91UHzi"Wt;\54_Uyr ϓUx]=OEO=s]N+z9I*mna;Y a=X :}D]/wl5ܭQk4^&,|>oh˲Hs$F)[3]HRכcY+ = ۄĩޮ_I2o{ePKVl SW^"8}t$UaQH,8`$fT-:)';ިÃo㏇lHBX r{/`ƴa]F -Lu?iB nx Ã_7[~58_7{<P|n~%,[n ,iBli%xףH<Sr?Yy#CbBA@y%` l2lZ)0|ٙS̗I0_v&|ٙeg7].yo1 }ٜoI ްdϞ @<L*ی-,U=@9c|+]x/3$I4p1qx|WL1 %,dz-}ٍ^Ӟ7êVl srW,kblI>K{uQ2ɤt.Ime5YOIiOI5.xCVCuOUYoeEpk]TIˊj\xZ3v~cxNv~erX옠)۫VO4$WiԼ}S)iЊ3eznwCDVqTHMvAVpDE+(VP%ZAh5 CNhGhG)!P ĝBB&`8G8G. Q\BBBB1;9*DA;*@;*@;8*9*wqT@Q! Q!Q!Qի q ]8*DA;*@;*@;*@;*@;*@9*wrTvTvTvTpByByG(. QЎ !Ў !Ў !Ў !Ў !P ĝBBt٧~Di[f?zZWt;* 5Uʎ]K'/)jcuW.@= }G)s*.7%A7tSdӮkJapt_RpŒ!<wEkC+FP] džq sSN ,!We8ї4;B_}i#CCQ KTC';ʙjF5 X!jlGpS PnTá K5DR T0TC(g!0R TC,jN5rBQ d4K5DR 0TC(g!TrF5aCgCСZ2%Z\%4;B_}i#CCQڨvwT;j\dW-uR:UKvqRոjjlGpW-uR:UKvqRոjj\F N5ZW-٩UKmT㪥6qRոjJ5ZW-uRT㪥6qRոjj\dW-uR:TKO ܐ_\<oLA EFIBX$[RòjQ iO+>M&n{%‚4Qh4O+\HU^aw/OWɅv!}#}yLS_VT|Go͆|J4s]o8_ۨ&ۨL6*[_; ѕϤHQi#"qwXగsgl|ݷ<f_bIGVKTK۶ϸ;}5/،iJz4<6Д&VS+ OjJ'7F2^THpzr5т_H|F! 9[$ԟU;Mc|bel}ۅ߅/;,΄PVK?D ]* IΩz}& I򞨫~iBBPB}*ɪ pPm'j\ϚԿErPMcÞZ:8,I`7ֱ5m.#oŰT?H}3:~rD~NjNtE[ihKLJZhxt!z.g[sJ%A/|Ye"ZHgtUE 6|Z9`â[va͸kM`<jF½_' GjsGlbE7NUxS!:] _u>ENSNb~P]7XV"/Mѵ+tQ~O[ug~x@}H7 È[ںjqKj,ehت۝L7'lRZv0`rhvN4}v=;OT{Za^jp4n 1TpsCҴv־}WӂY xN#jyM EMGzzO.}Z3fet5({U@FzI ,t횺/]N]: "v/njTy*gbkE-O U>)ZeG^֑ЋܧM%2NK \a\#ѵM-)Wx5ij]2j@u!.MTnެj.=Ȥݻb38}Z}ڮ7g*襝NrliLW='̥5#oj\6m\Y׊4ą`v9;օ"XO<$*`m`kZ:}]ZoMV'd+cs t>egFF;`X >Ot}WW+ìĩ(E{EEp>vJ@cU)9L(Q.~v~$3$||6vSř;Huge?+sacˆ/ led׽3'W/}< W;|o<LӃ8-Gzy;I6w:bwy 9P~.738 kNR01<Q'zG* !ZSQĴ=Z2L3/{Yy8(yzrzة kd.9934`ҩ$oS?֚按{nRXBۚPd(I:5Ԛ4+PK!-ua ?word/numbering.xml]n?Ȣ[#`22Zi[(og>&Mi~!RK"U"$J6*ֽuw:]=l8In:#\`r7Ln:}p:Wy?&I|yg?O߽\'O8NHf/Mq>^wc<>t2?&~8/%_t2g<gq4N/'?M~C?Gk7Ln:Oir]ta5Ek5c"s]$ q2ϯMQ6I2{Na[㲓g) H/ N5=RRcF]Z5# f͹T6mw0}h79K'Oӯ 9ebi7諘ufcC2IlDٔ]e^ZuSvi0i|绛OIfû(;B}.G:7|CN9FԹt<uKxSߌ_ ?Qv"(CvLTxu. bY___W~\`yt?0Yع8|ӱY>~߸-N}mn5G?|P! L`%z&݉ɸT[ī,JMb4:5L1ef6Dbc0C"Z̐.dc2 LG :y u+tqn<C${P$hA6:Klv]wh]Y< )\A$+/WoFЖGMcd\G4I泅faFzNFyS/Ɓa2_,~晢(`joLeKe;[GͼV#DAoi뷟Zlkǚ9nTA>rsWbJgQS;WaZqejw+n;Š+ijXqW\Ɋ+㭸6$2Δ$+/_:+7fe̐Y 7EkL :X~:^sx/x|Z&B8ΕK|$ic_8_@ ĠI  -툁A z%˔X6d5١Uɐ&C옌i2ɐ&;C iSd v>g%e+ϭdo!_A|e+W ުQɥ){ac+;W^_xIxFFb o3G^ֽ|6og#!}#5KC/A;Gx#8<kߧC~p;eC<OxP{e9Mb<n 515^#851[qkR^3]qkRrPC*߭X&l"3~$asNj<}1XsRV)+6 )*nq*LDd˧sV!,rЕ/ `S  @moʤ w#7)u|[ <WotgJůo=E@x I@7DrITP0EH@ 8с@t :k܁&xP ^eDс-\P|}t}w{aI`oʅyTDy%^C>_@x I@7DrG SC1~E:@x <˕ŋ %wk!ihpx`*?p>tʏ{ʏ;]ʏxʏŶ b+DۂO=*R\(@jt ]}+t^&^!:(㦛5@L@%Z"< mQ ᑜBr )$BrߐjI퐜BrOr+JkEIM[Uҕ: j9Z+HW߲tUd*uZ=R:~ +HW ]5+HWf+ҕي{GU'n(댥+k-t -{ ]AjRZvb\[ϼK~.خڙ~_%UWR)0 14@/ZA Dut H Ŕ08s1n \r]u!u+=BkkB$rkpp_o}&!jIL&_.mPʞ穡KW>"WV ]At UAte ]w$]_:M\ّwf[!y5UH^ yA*[t>/Ͷy'jY<ҋd~ ̠i-:#fL`thWf &}b@_;l佛#<l/?^v0TpI\^/ c?c~yGZq{{\؎"XP'4&2||l}@lAlAlAlAl5[q f+lŝMrB("nLYjX؎vJlGuݮnjکZr zG;UrکO~TvRL=WLMЕ&ZnT/TP0\7T1bWCMȨJ]jbj ]QMP3]hj&(MC}F73fx?QPu^-^{P}E4叫B(/WPMh]②jn7x+)U6T5:8,+j6N3PK!6Ur9mdocProps/core.xml (_K0C{v'ŷmI\oom{r9qMV|PԈe`ʬj( F;hT1a=yG!K$p5ZAAP$Izc* ;.~ pI=H)FC L W/ ʙSspzG6u]MkO}5WߕTR0G iq-qvT vIK-տKCXV!LY bлS.J&>Pxg PK!G9P< word/fontTable.xmlԕM0z(!v&@@:H̢Lյ XGd'd8CGo۴s$ RHΒjÔ\H͘܏OuLJp%]Q߾qyi"4MgĴTB%LJ ­{Yr)Mgk}cw*i)E%͂%f+=K1gK=A"$XQqڂͬ3*q+wfV@Ds4r8 /JL/ P SK.jfEmمтhCF/16QDh/f6rʰ9Ldf@gq:5ׇ #xo +T@<1AHsCyF]>\D7>ٿwDFuH5"-.u'2RfT[&Ght@bih5G̞_c ::9)ON!YFΦ)qQ vP~093q (܍ |(zMAQZf$.* Ԑx&.#1abIxM?}z+F 7Qm ؚ= [Dse[T,O=R+w ؅J;}J%NJ4z'-QgJsi|X߬4͸>8SN6 PK!ѝdocProps/app.xml (SM0#ܷNrB]=[ݳq&c[l3Nhp9yy'Q;)YU`k=l(m+)[ !X׌Eu^[:\%RuVpKټ1xE-7~,G Wu*Oٓ H5ifÞCi݃^r6"B|Q81e ^K{DUpuX< Y"{P/A9yCY_ 1ELN!+i`K]48M{i;OЅ"4yY|R6I--c A4 iO륨׉C0x |n:l<V3;K?TRلo]ڐ_=&?k<Ti>eʗ ;{bNS~Ow&UKiWKf}]8Z9PK-!~ [Content_Types].xmlPK-!N _rels/.relsPK-!4zeHword/_rels/document.xml.relsPK-!ɉ-F#>t word/document.xmlPK-!w˟;Gword/header3.xmlPK-!"'P;Iword/footer2.xmlPK-!O;Kword/footer1.xmlPK-!;Mword/header2.xmlPK-!n;kOword/header1.xmlPK-!KuHQword/endnotes.xmlPK-!wSword/footnotes.xmlPK-!;Uword/footer3.xmlPK- !uΣ''Wword/media/image1.pngPK-!0C)word/theme/theme1.xmlPK-!ٴ?Y 0word/settings.xmlPK-!&kyUjKFword/webSettings.xmlPK-!hq͔word/styles.xmlPK-!-ua ?word/numbering.xmlPK-!6Ur9mdocProps/core.xmlPK-!G9P< word/fontTable.xmlPK-!ѝ׶docProps/app.xmlPK7
PK!~ [Content_Types].xml (Ė]K0Cɭ " ?.UP@֜LݿdȶBsR[W'y:f Je{{]$0RT@ƖdtRpu`h^ W?Nbb<5G=trXT<|rM̜%wu]ʘQF** }iQÔrUJlI;3WIh_K.mФLwlErhyCtKJ-Yo0 =OÃ֝ԾH!N/F˼!n#bX;w" $=//kk3>#ϟĬ!N_fW$Ux $m燨Q<6h"AnlPK!N _rels/.rels (j0 @ѽQN/c[ILj<]aGӓzsFu]U ^[x1xp f#I)ʃY*D i")c$qU~31jH[{=E~ f?3-޲]Tꓸ2j),l0/%b zʼn, /|f\Z?6!Y_o]APK!4zeHword/_rels/document.xml.rels (N0EHC=qByi7[(ƓǑ{FںZ,s掝[u'j,Xf,,l.% ۀe:m&m'mـ6= }QQijދCGY6f'=,YH_nzOo]Um Ϻ\+@wƂ7 $(L zn<F1*!h`c"?+؉yc}1!uupcZPGĄHMau(pRp Q)܉1> mL/Xy=18<$*n)ViOOPK!ɉ-F#>tword/document.xml}nH wz 8"3$X,.hxLZX pu$']MfCd7E>o΋? _HhׯN~p^N$uùDKN?ܟͣ S &g٫E.^Lf MNoY%Uz:n_FWW{y(eͼ$AYnx&'tѢWQ|߬/K7/Oآ :Y xDވy%L)/c/@0Daet =\dܱqwd߻_Jj==g3 sm@ g(;C8gɭ뇛;&\Ik7\`yos^j7ڛf=pv&痖]"ؽ DhuIh.ҍ7W'H=>FMM}zQ4F돦ޕ RxO後'|>sN>.S? xN .ADCm/"}~_,<}!XH D2}Q<_?;x+%kO4]3Mts, rHMQRO0R4Qr=R.*0BVKS‡ԍSo^XCm$$=?+ w,e%^|睜 QEU5!Lݏ8tOx09-N9jHvd*`tdcլ¨訒3-`~-eƳkѹpر*Vd{h]ŠA+bEB*`|T<t+b/?xPd]̒\b:ZhRdE';u.puKDp$~f}ht-$OVnm5#dfk9.aBuP5bLכDGp.l;߻@ ["RdijNM> E2ũ^I')X@ʇ#|DR»]cqtMmMedF)0#lENGUL_?@tp7/9Bȡ%*iL'd-`cy4La&LhR:.,,|d|f[tĝtfʾIE"YS"ݔ>]E4wJk-?g}s,ʄ E'e )R #0NMv}Oe4ioC]7eH>zr\j1^.<!Z1mSWԍ PB#!}#,ETla~&FFm />r& Av?!Tf B #OErjj4*.KTgث~A {Dl AU4KCIi#֖c8 LĴϻh emKD=G)= :ЄB,\u#Mr,(j|x@`~V! e#kW,Mϼsm?$8L>BlA~K%i/+ŰUkdwo袪(We[s綮G*lj4Ao/h;F0a,Mq6 /oΒ4ğT"[ whvZ ²?,9ve#~breW Mhmܤ8Z]/{ FKO=SRX7M 8}(S3 R2z?yIȼiЮΈ/cԬ>ܻJNG0#bDQ^<iMC"3c^A2Ox$5)l̛a+#)Hzjb ˶e-l&3Wkٰ-(hbɺ^)lS@ܲj{d8Mv57u8'Pstb<sf$*'LAI@u&YTY8 %vx`PImDW!:2mDŽ˕)0@acNt~%S[w ^U .MLt8@+sCp`g492"^!"M=<'2Q&?+, *^'B`:~^{XamAD H̓0cH;a6@ȤA@f$,2Cqj7z uޮR7}),~ ̐VH@IDaX.LVprQXn*/DlHd"G.aeU橙dnW- `!UŀddO&B{^ZJAQj2b~f6裏84 O[(Do\E)9 '*pIwIz%q mGOLwlao`:`ߦUaެ ,,M%ݜ2BnŽl< (H#BFF B/}PHZT8 ΅N˒n4lDeƠX%azL~,l!$;!y`EMΌ>I*pC:+f~ $^3IḘ7և/o<A,;B:-%Crk'"˴<80, kf- ~"lfHlw*0ҟz~xA(!^#L5r='< 7$)7x` p/G4(%H8c{sΟO{XPmL nE7st,W!Z2]w9Z'HۄؓjIM)9Oˏ@50F>x6_*~l=/S~n@O_2Hd_k`$6`c."<`pOGd%3BJ"9RgXKeoMфU68!39qBmM(IU>angenHkqbr%H_ 1< S;\/nddhEw2/ ~yb+$p~` `[w~>'.M&.xgGG9zhl2 k&\ :֋N>T%z_q1pgoFVCh1N-<{fF#{O{ſ\ ?cHt{?% } E7b e*IRYQ' D7)>YO} hLjfa@ Ҹ] f붴ɄP|RPa[|D&T(u#!)/Z; g$X5Bt2^cpQJgkDaO'N`:ܙXR{"9S0H*,>t)jtMtF]bWilhC@Qѻ8 B8mOO?Np"q )4{Y%? f ݐ bvo]]!M&K=nNK8ʾ<fbG䙼n.+ۻ`3'F_g[>dC;# J<Κj wdx;ͻy% t\~=Zx Tw =/Ҷ޻ % ? w{qa=CF#%h`<f(-{*+#& 1,}y}'k/o{cBɾB!7rRk- 2PyS!uω'JIC-ZfÄQ T?cQ& #ÛQ"vz7k|?vy"/A?̎Yu_1'Q~<`u EZ$%/a,o$eqyZѿh jhxd4򇙪 8xFix5d DXRkR:3󚌃L[R.~d62x^D)A1#i P6T @ F6Ln*MvHTcXxKR݆CeEM7Oҿpd]KZ !Nz6dx-4L3=..ؠ_;Obî| 6g,Iм繛K7_T`ܜO;kv%-yd; UMQW+QԋTq5c+5P( %Q3YUL {6Xp܀u18L,3ʴ3VZeZ|Rs ~Lֺ)1JRoklΔ9*iO%#dkE56ID"YR3⃲ ܻűw؛\I`{z~qxU)c ,1y8ǑSȈLX+@CMpeIKUEtS3&S T_"'mEvM;p}"4h#.+0קHhNK~\MSuHO+GwQK%qzM/R qor $q$m"[[##:j/D/Z;DCo F -%2pIv|'+44 AbI%-QөRaiiޯQA_?mp&vWTgbݪ"c2B~'tpT֕JnkNnZ&rLɷJ3}~lz$/[x.8kh߰)a~ܶ ][<"*fHT6UniqYJWiX7\"BW U~(7H:Ox]int@[s(u݄q|W_> ÚҪquuT-|8n=K z݄,I0~C eM ':ъtN~!{Vt;ɘج X#+&‘M$n?"atZHXV4uPv8z88ۺ2)~⠶dkk爡FӃ_>#UhDۑx1f]Ͽ|/Ƴ$љ|Im#JkPz$¶P鯱zHwG-z~'ƎjOEU&Hq|wnmMӗq7cg-^ ~J.A)+:iL7pw nKZkeudDם]ᢪLb)AU hP7p4Zއ ±\ƀ9.śv)#!/\,#?ĵl%]֦n%btԟVR =(w>5GcK!Ӎ)56 e#띿_hNZUd;.屮 Ɇ`ß\#q,QBr0Z!, Ai>d@fs" ,7BZ6d*Ѧ Iw$>6JiEZηVusDXzqs7%uq]/ "'l!J GQX9a3cNpW>Tly4=Mg;=.~ugZq~u`䩲Ʃߥ@W$*ɜxӒW WVhH,WET[ɜd*`R1@bT6 J5KDY}\̕ Q*tܡ,\O=sd̒9.`ai%seFl`e64릆s[A4]G|*PB  kF*:k04F]dzi.Ƒ$q:scUy*.SR(~Իianyқփ9c$F+R$MEsZՏj'~@".'tIX7"6lꏕ͐UV8c`b_⡄>zXn;y*ie?Q?G5CI$|KJsU:V8|ȀgS4֜Q9RzRRؔ)9:MHyK;x(25YNnդ9n[QTUeVOɣ}CboaV{޸?2I#yt ]ϵqn f/7n[R,G؛b*`656)9=5:kk0o'~׼wP(wOI<)ZRn0lSn[  &a]tGn آ-UvޙSSŲQWԿE<,qپ\<7JR5,Ύ<"r`%,o2 j7?%5R KHGh"E%bar8.`4jbNNQt{'41+]w9Eyt+,Ś%[#?Z*8mX´14ߏ* svp =ְ)a4E>uj'}+j膴wί`z-XP}>Ξ!p\w9y!g#_͍2_{r@ 1,r,8[rB߲P?-sqfl1mm*a2*.8,@KVLSmJ>«>Ԗ`|ڪ#Р4硡őDW܂uKģh. B'`w  v|LJ}I,/ 핊7kqK{7nMuYdm/qN ])ENGkqф& 8ٳq]_[-ErI&y7:U]DH;CRʼnXRFВ4{IΩ5rR6zԫ;4-;fГ`cen͆ B;'ɸ Z;0QUz 6,U w9%|.q΄ٵ Ŗ)YG,2#A:gSح5㦔<ISb:CɂDžߊ_@KޮG]Ge{#*VU%fJ<V>he!-བྷafk3gfxֿy`K!K)n8->2S}i O& gEvo\QL۴!?,Nnh,xq ?,K107$aP7JA8[<d}|;/ $k=CuNl>4 %86;/ix'j8?ޜUF/AS,͸:tPT&39? 1 /P*ᴁj""(̍+0ԶĢu-XI=/#l_70!\*CCNVf)]iAGT ǚ":&WAmj`>F VL%0,F[f)hlTڊxɟӅ'j,[aKf5/yu_+If %mx[r|buٸ⺑̮Iz<a3<u37z<W WMtwmKa,zcyH<UeǭFˌnᖌؚNDL'ӑM5" g5yTVEÖmJND'K FH* Ad)]8pECtGG Az*zG;l,cW?fKQǞŬa۵hħЋAyu;Mc=`DR91 $,酛0oYD~4e b4[TFc~gqDWF58҆qߐK5 +SKpN(dwS;_ S 0Q4.bRg0+14ͼ"nͭ؄-F!y/傝?Ktv{lwvv7m:MKh|h]6 r??hZ*/ B~m @yw0Oi,TUs,VC@ڑߟNhe{Rou {a5Zᵔݓ m/wekOw?NLj$}w7)cc: _c?y=;9X仧x~ɮA!ANw@~d]}?ç5@cEv].50ЋwR\ucˆcQՍrzi^{[^gOfVS;v;ArX:%Xz}(xs3cD谋! o)XvNMǚۭis#oc%i`FsCPٓl)pR^\i6`g zك߼)nF/fY^,˪u˨,>ʨ$dI,Xy@ˢ&Z]CL{cXkNbdlT -v% tMЭ.VeXb6*>:b΃zoA0+14֘%CNo4oR2Jg% 9l-6ͽ+?Krbe#6$CՆW>S*C3/lee'wS/x[?X |t skRqZؼl]D:џ(ULc9Ta|?`I]X!=NHٴ hNt,w!GX \?/7aA #Օ*^_ eKTuK**h/ ,ρ=zYWȘU,Ov_C8oUMx2?xa=_WFmQbm">H&IឦCE*jDvTH#b.yKiGqf (w^2Z Eҿ 8yP#*%#҇(n-`^%RuEIek9@1xVDЎ@] A讫&Yd[BʿX%e`7 Wȑ"KԄks oXI-zV#!PLi) }aNJ"92k``SR`Śj^;?ZI29hHejKhbKxODGOsKF:F|ڷVSS \} 1oؑ>hдM[ώ}q B;lPgnc( Q+?5!wLv?_AW {`Pt/,my/"?C^<x~nn1+-z 9:Ķ|[ۺxSlgO;n4Xe{ bC!1 򓷜3,tm~x %K۳sR[h y85E~9r+,n$KpgզW#̉mɥ +"y?CGN؛,F=FT6d,ȩ>'&oHHFG1 5QB[ic,ZʎeڪSllKة!N4"AunNil0kyTdKفѣ1Ls0z#(5k}J84Ps=!b]iv9t\l-TCxJM}|H o н]^Ljm2Y+GM:`D]C.XT: b^C 'd(-p5]5'FQWEDȗgv)`!_ n*<s&VMlVK+(*ECZ5ڞ*EO0ytp{7LA0Bp9`Bx"WH̿.8d9F.bfYriְcIhm֕'hX"RmC]<DM Iwp'] u1W6bn" >m hn;J8XCos$d /JƄhU%ƗT0u[:e3`zrB'*nB:@?mIkd?C[ -)1IeW$ 8gP ˠ3zwX% a=1[P1l!lylݑg9&u&hc@ ]] x{RKqe[-M,}"tHգh# BAbTWp9sݶD#6h%]@W B}"@6@T0%'0EMj~Tgqgx}LӬuqı6Fklr"<&+HU?Ŷ]%j0FlړPG1U=}sI6hllVkK&EQβEjI\`KÍ~'܇fvb\H!lHO3}@kn 2gJ@VD[ T}45EDZF֕mЇ>%gjkcD#ӇM~h w/ 'Hh3@Ghd%gei |{;? +4ӽ訏/W%Ab'3Mq⻯N.|$'Gn M Vb^s8pw k45 ꍽgul0g(lsJiK9w. vI‘] ܵFo96;}^ώ(lN ~8@o85[sAF)Y v[=^:}jv  HȃXO#[+\ԋhwƔqFqֺoC;*-1nQOƥ #81wüǧ"rG<R~hSTGH3/9JopiW{'7ԑYZ8,GLu:kq6wu]јsA}x߸2q㣒DC[~˂JHddvZm7G*L;}g-ۥ@_B?VwG|c>n{H{DkEwO:u[c C7GdSnK:4|?hh aæ.[s0لd) . TЇaJz@4Eϳ/i$lRH}$/$EaSM$"#א,$ۊaM4rHOHpW'EzBnN4 7#ebRbpIU'Ĺta\פnul78;mi\CլܖJ)Z{/U%qK NϷ +I"Xr kR؈5Ci?nNJgVURnR U 5qBGdeȒV*InƩ5غ!雊r9.7ro$ݣs-j, Y&`Eέ`|F " ӑ,)h$<i:2F!lXS2T%e(ȒxG[Y٠n&j^]ð @<A`?HHVVTr%ٮ3y@V(ϋ{CFt;s[d@AMVlt%.@ͥYY26I}Ԛ?n-(^LUW$;:!9*Rs ATkÈ!mu.M\C>&M׭`翙hS"¶u_V<l]9z1eLmS)Z!O"nru3!( yk0$*:{:׾=\pآ΍}8h4&9 4 T+O,hI{\Պ(nrq.0Kz7Nxh`_rL==s~3'aVes$oڴsJ7xlR'%LZ O},Md$ *nc:imR;9y*8:O U4s[W1 ]a΀h)0j2$ :%M0ɅE>ӓEWȰxή͡cĀ:5Q}]!]ŖAUZ5Ќ˱ݜ4l&;qUU_̅x:gKah]j=Ǐ#F!;^@31.Х1xtThFu i+C/"V׋] '@dtEiDu<'R J_գE[pBpcOcJp~Lgt^j)S&cSuջ[#-A<ͱ=Gظ0b UF?!u$X4=LGøwqo. ,~iD-aG^B:#Vwi Fv!3 H~gs/yڳnrZH=E֍ == _i9@k"c/i<xس:DȒaofN򻾗 '[GwY G. zcqaABzawiԍW4NZswûXٺNNalaw用B3_ _N W~Z/) “5.ZG8L"Zs! nǁ~崔k86+d(zY)WN_rx c64:51ҩ5M{` ^L'ZLω7X@ MnAl2 $PL; pNDSp֘:Lm 63 ohB{#v6iGJQBC 2`ƚ }q)r0.dQ7VsAF{.qg1un X̊[anD['&9f=؋9f jh*gHaumj<ip9# v QGddMѵFWS㠪m]㠓5o409GNh9 u p+ٟ=yiՇ9}Σ/Y!4_m}M"V"G25C*4Z]bæ,-C kdW<ɖ6m[rrU|rp?SD.GI,u0r2ud)9'V, z -?LR7 >"yisn`BC2('Zte͖R/怪T"rQ?&yC bWg.צrd]4lG+ʊUAS.wՀR84t]oC=hw?{׶ DOy\ }k )6JCH7DH`l'ߒ/kEu⮣xf:3{{)7P3VҊ]4Q/Rq0Za9%M4Zw!aN5.g(u%A<1Jg4l;1bBv*XY~893PR=gSeª_EYr}1}? ;ι iMLJ1pb薬x%`/&`b ΌMOG|jb`ԞJf BADHy@#<']2JSr^o7)?4VI!!m'* t_iUrcBE9JZ% *irMk4Q3khM.,o2 (A5VK>Qe!_;נ*!`n*叽f~aWFB)aYfCswJ2Jœ뤪a2$NlDpddDzgqI:톈bgC%/];ZnE{(f0mYRaÓk 4Q)Jl5X9q alV2^/,G;YN⟡-w?ĆF>!|v9E䈆UJck.2Lj_]?x׀%Kaa?<(dZr7~u{L]X40$)c7Rzv$ d;GT-7J'Pm9/^NڬϺ&mѝfN0 8N.Tn8 ]GϘ,DpI ǰLjwh.GNƼㄔpBP5$|mu!-rsbRf!gΘ3p;j@}>j@M-9d8]M@JHtF?uj|cF9Jx5,Gǰ: 86^x>M}qlP8$br pUC } b>g'O3w, P`J,D`Uv8SOF=]JYv(9s@O-=OJզ(=5X+&ʒ \ <81gW̱8QEF2-QigY%؁o3@܊&so2.4<+  &d*YT<)H\" >L7{h5 ..ֹ35[og՚G(yիeSܟat:Cb3%P3{Z̰]iL\%CcCtAW]]$KO JBF9K| (ؙ.W2KsQٸlT[Y`1 ·C).x p4_D$r>ʘ+&vVe&6Faw5īv%,4[P )RQV(pW)\Pc k* G_y2F!:-qӢVjHcQ܂{Q F$Hk IR?-Sysa[ʵt1/0p 4KBh$}qKͿU+0~?-yURSB27h*XI@E|gkM8[BjAZ)gZز$B FP4w8Š :]܎y~/^Wr앆d'L66(VМ|h7KkkzުIoZ Q3pn} ַ4[Gvˀ$:ƿS_)] s/)ͅ4/Bʀy͞(` xcpI{#!IdRZb ($褟Ųێ.ݡKVLD4[DX]$EE@,v+7wLf|+?afe ]ϫfu$?zr6| e/D7w+{VݓAf)O?\8U-PhpB +7K1A},beg_.p?^d?%B[oPK!w˟;word/header3.xmln0+ M[i1&X@ n*M80x<wZd$$\MF^_Fw$򁙜)kDF“ՏY9Dm|82Ry)4c-9Xo0VS[ Xuݗ˅354‚f[FHw,ȵT2l  L#F{AmHԛ!Nɻ YX^iaBP_Jwƹ4,H&juK&`As"?iS51OHG"ߜͤ9$>h7~p?m.+o;ey۳K V_ĬJj.7[+T%ԣ&sl61`m|>{hZ7#q<'{BRh?CgVa.rg_oPK!"'P;word/footer2.xmln0+ YVp Vmeh~IJUp`x͛VQ#`rLc áfLfykfepf fz^ TKC4\\A8/ 3 d4d NCNnY/RɰCv<1ڙl@Ll/h0c;>e„"uB0p!WhZ.ʱxb^$>#q5G%Is,9{#n/k_=ey=C ӥ<U <l 8P,]ߚ,8e9)riz;_ߑ[輿^h#~v{pDjNfzS) S9Y].W?PK!O;word/footer1.xmlQo0'; '**RM:mZ>l;$&Uiwۇ&i `<erJvqvǒ+ Wݯ?Zuy1l˂1 keE[-Tq.r*-K~f J=׊F^94_?#Q?k턁51; SLxICdcCEʐph [h:-EGD~yHmb^Бq̸D5'%Vhw*9l>Ϳ9h[rdK ׉yhe9@lH,]Oߚ4\^ؖKwed7{ysʟ.ooGFU1lf<ŽQ SGtPK!;word/header2.xmlN0"߷Nض)Bt!08Ncl'o$MJ\d7=WJF5w^dkfryy]9HyF6ܓşy0[,#e6Գ+c%3ǎ(1.qw_ƽR7kǩirq ݚ*po!BBAv<0&#i)VPo wLmҰJqqe[DdrZ4{1m[]1>(z_W[sg>9wTvOVmjX}OTXZkU"lY5Yecq8I-8X;$׳tCx,7޹J:6ch 2#r]iWPK!n;word/header1.xmlo0'@~Ol*ڭ(v۴vkL_:htg[ܼr 霑DZJe7x?N-vVd+Y~m;/ RsJan\J I;%`)<8!CT?my #μ9/-NV 8 5?CQ=)j¸4`1 CLpJ]ʉHF ΆZ6>Kzm5zZ4;+.);"=bq9'%+{H9:c~s^q~kΣ_"o-'ozc'd zd0=. e:Ͱ7(_b6>ͱ nx@ y[-qiuA~I^J tol}PK!Kuword/endnotes.xmlԔn0#;  C-QnUyט`/Mh~~v(JS9`/߿a^y6LyT1Kߧߓ"å4AjuS i!L\+Z!L9#Z)ܗyk3ASZj Ļb p#M**@KͱO9/]a˞YUZb2$\6n=9q[TSa% )* Eٟ*bޮVat RkXF9g/O8qN 3ᘉ1Zs{]6?ZVjh[2e<X $`dts5ڌ7WP5R#,ASN2 WazFjm\׋_z4Ui?jh@n1 (pn)\$s(k,>*WDf-U֠yw2Q5GY-KW7hN4hܛ?PK!word/footnotes.xmlԔn0'"CUԻuXC8!r\_ͫ, 7VH<H\UF5&uT3̿i8nd(֚edNв5`,n@P(/mqk1 diBeFR[ %5/ ]S'E)Ѵ@F*b']6ys.K`5CK] /4T;TYvvf4e<'ueib1=Im.IRkO>em{v^z?ڟ`|X,5x%KW }.1#Y]oMWNPnrM u`DAjKRGxtscFҫ]3EurۋU>jh2P|0~2h8$w((7/VH8{jjU5h]G{@9 zzߗH[&EL-G;բPK!;word/footer3.xmln , J?dũVMSVǨ v;vݕc73F$2H+Pv?-IBVru1o2mZ'rR2JajSBY*!i ,e dۆ24pd CMxToJE61l@Ll'h0c?%.d 6>#RRp!Wh׵.W-.);"bqsJ WGGst<z݁Σ]o"o-'ozc7d zdp9>2OI#vޛAo x cWa{Zʒ:'ߛ6\d't1Êol}OPK !uΣ''word/media/image1.pngPNG  IHDR\sRGBIDATx^|$uߪ3Bl̴'7cc-qkxarZ8u0e,Z2c31 -Ƀid~[U]]U]WGhݾsգ:}ιHz!vז-Ϟ=vj OW/?pH"@:m1+rwp-C7-(hanz C@J D cG?y  D=N0x?zO>k> x5hF"@h$0yaJ.|ξ}غZ1 ,D"!fzFz2? ) ~CVbLjI6\vw{![;- W.|cT3=!2zwv]]̙:Z}ʫjcurv>G/~ߟ| 8 hͶ7_?~n^?z;w L"@ P3 C]._Þv1+9tu76h)YT+}w3?>*S8Z3S<Gb'ߺgvZOήlΘ0?FɅmى.Ϳ\[&%\Oޣ_] na,02,/\3"@#EIVxybXVaLl"E? >Մj6o7|~ݫQ/oΞə\grrΝ%p'ϲkc1/*F D40T?q}aQŖ\bߝWWXWXQE#M;~JjV k~M+p2cQ2wz,G5 bmsF`-n-aJkO>y~10ПOJspOmw{߿_P1HkO~u䈱=t/rp2>E9(T˓ihF8!D4k-/a B/4 />;[4B̀;"_ Xcy1R_o˿rr_^q~u)%G.DWāG8r%_eߊX@e ~>?ǻӔ{sŽ^Vv{v/9{צ~'mO3?|=(gϞپM o -^g?w/Ogl׾v5yYbdRYR+1wRۘYQG"@@- ` t5Ƽ,?Hc!>rER!{4I}|9e/~7a~u#b]?4!VԖV. C5)AJN @K#Nя=y,Q}Ÿ|{k?kh^ᏞyIpLsL(̚)҂[l?W·tm3d6 UongtYX[$g@_! Έ> /<)|&˱y? c1}n!E[H2S m^_Ykm_+x./.@OW6\_pIw|k(b!.FԬKj:*l $"@. x殞kFnx"F34]-8"wgfsg6Z)Cck;Y "Çk#%hG唯-TM=|r}y ŊxR I<O$M zl" zbqQ8W@3̌/߰pMB.F3xYFI]X&h[H3ڨ# D6x|tA~ rx HqDHF<Pbk5r!F 9YORR2 ͯKq<Y(.]xᅰ}%P‡" ۮ͏`#|u||gaI , AcD)< +I<#2=K1:~n3=rͮq%)LC[QO"@@p{F: 2)}|͋.[nrvc8DzgJx) [|o{3;[W0uς S0 EaTOI 5!P0jMㅀIկ~ o Xl"_UK(̋z_k-! U ٠MM?T |2] vǝ.]_:ܐL7>dV7^lP/"@&?^VfiJ7IE)ǐW<P <ޜ a[p(ݰսQfV6{>;;'FX'`7 CW'Z{ퟞ_QuP"@jB?,uLkfra[͆>6]8T,3.YǞ//3'*wFO@hiD- jX3_ @=~#G/E$C"Mh\}j1qAk߷%"u+?rL6Q[ZhEҟhï[l>{\+ޏ6ЙoMzil><w}xA"^ 65M_d mW! ڀt6OwiM81̋!TBlADpz-7B  @@%  D7.t;#ψ8?_:kfba&BX1hvUCDX*yF0Lkii͠촬^0)OZ@oc??7>]a&τ[z9|޿- amyRa6> 9QG"@K0˗"70<I7qp'gh z|v<_\gr@lUTull!*hodaյ'W^_ SWvmM H)ă\X Ef| nMǴ?]dU?sc?p?lh=YQ<j)^&$D%QWMJ+N=Jknbͱo/̢pM$f~В<1%2D4-lILGY(W+8 Ə,PJS?ʗ4R@Jt("i 4 D9J2tU-/r`$YrT T $H\}4^u gc&|R5: 'DTʈ,|/5PoJFb ).h- nSojE]W/- ˞P20KO*웚]rnu'/[C}jE5g57'G!$t J,Bp'14IɊD}a eTR! ~Yhd>ev9+uFY#&SU.~u> FƺdțԼK=(٨vhF==%ّ ed0JfaLzYL@~/͍MI(L ^p W{1869 ns#:X ` d 40``GdrՐeܘ.8ԏ}AWK hDT*"@B2z 0&=%y( x3Rwu@$?"+-- n(Cs%rBW2)_4}Bdž%S"04L"@Q{zd%p4 VvG߃ 'ob~z.2H|NP{,/Rqtϟs7L 576F "@%D_Y&LiG x̋FJ@1{Z&/ )٣e eӛ<n#CP S>M=g a"2=!2OV< didp1n5 5~s57`A8BakΓI 8T.7`J7.rR0>poXKvieVdEG~֩O+?$2;ew?Xp$"Ј3=P6[|+eARL ]!m 7wTIna=#o{[1wu!t-Jh8 DQ".Zbg)DUQVfU"{̋Ѩ aLa_?ﱛ' D(madB b| X(9PtGukyޣpg˯@@(%F/,ԆDIà(Il?  $@`}rgOQ.4O@ 4K #D"@h+Sϗq'&eX&SU/sc%ߊų"%D 4¨9B1W[<011zAsnؖcuiE.n.Q7"@@;h!m'%pUm*}l:5'jx>nT߻6riֽHڏLGn5`EU2}>ٸe‚}Q\<'*._㉅p8oXmHM1J.GLirD78@kD*9{~*8|]s5h<83r-xԉ[nP|2rC?˚u c'<Zc{Q̃9;?-SkBQr? =flgp{ǞOv]! 0K7K[ͬ]>w<3Or!(6t>`[X UAN|qE3D3nZLϿgzv/ <qw{T +xJCzQ_p!~N񺟩E4B^獂euFI17Nau@fԇԗ^M~a{r~HQs:Q47?ͽŇgOq=tjmBwm:EynUA| v!׆,oh {}$fM{JbEhk.H_Cg_ڵ";t2uhGIJ>%?Mam?,T>`F˺һ_('& P ٮI,2ܥ4n1)N&ϳ Ń+=j 鯍ʞ΋ɠ^Xnfԇ4@-$gR&|$iu3OHpeNqdgwstUW_gae7_d7oCw@E gπ mbkj,0Ŷ]sW:k^/-ۿڵʑTWa\&źE/) d^)I*=EH0@F.m>\pUH1`^/M12a [:5G;V.q63_`JACY7#eEݴ.`lW8@TI󢍦hK7YmR^DZZ[58)gz^}-{2XI<]\v˵kO9v칁='_G3-rω;܎2)lʴJ0SR=\õY#/O{,po6,fd+(C'QJگ0U$%@eJ*Č,CVa!V(b g ӫҌ՞hVUc?nt8[h!ΓVc,Qihq1k0bB' 5'PEZⅡt|H {x@>3R~lq)߀mٌO<̵W[!,x9$mEtxhhn J[:k=sXl*hz-&GࠨÊ@% :\uGL0 *Sm"z-g7)`d>\ϹUfoC#AY M(5[^,,\HP̚xbWD y -1ZN?P2FSG\`j Yb^kU?/I "pAýѨy-2DkcZ52!@͍)}v&\w[x3!0Gv\!LxW'ABOC  L5W}:tt 1![Єۢwh"T*=trw7rPi+Nb MQ-YVgLGZmW}[ w39tt_9 \Up&UȘ?Oin p"""4> Ƃ*0<s0Mk˞##s(sĤya4b9Rۣ@|j%^ % gzRA#SS =kViH# BɹԤʹ siaO?w}{PT#SɞB"OxɏHעQdDGC0ɑB>YDK R"CXˤ-<Uk~Is~^ޭ '%PqRy ^zz`';C۱ٳgyyѣ?ԯnBҀ,2-D<џ?eQ@ \.ɛr<2q8gQ<syAD1KY:h2ajegJk8y9d~ГgT7:5ali2NM Ky5WKԍ4@%aC3Ka'"g9CCI6@a|ˢc{;P0jG q<񢆳UX8~,tF* 4O#Nr񝉸I7;SG.Nz(@2@= % D!ߚb*5>qi_Ũh0&"D-x٭*ԏJ Q)9GN`m\B"@JhiMMyyg%n)I u" 檋Ƕv9b^[S$5q$"@:@#, 8s|W *^]!\ gCeZ\D&Ο?_\>j U'q8=Ba6@]~eBt#ʘ9wSD0՗WFj/VHB@*0#PD1>e&O=w|Bk1|bO[{c3ǐfUEV@7^!| ,&8k,=-4 WۃW5״XDi])zK7,h&8s&ʴC**h4 pU,lT,H*x<+cOGk1HpDX Q2\ei J,B:nE+]fhqUW_Z]}򬄅Xo֞iojC#&}f15 PU.ٲ|;MUOA[4o8-(2%= ^FVziav=yj^-!(W,~8#W<'^|0'Vhs!g/BMj s[V,dbD4W,\SUfrm206BIUތ%X#,4_߸6*"PZZc@qW]fVU]l΀ZPS``"gP }%s5tDyuծeڶ]scݮCi6.slacA8~Y*M޽{+02,DBDhmx^"jdDA $8ő1UO1ѧ]C^KaiLK7PpX7[NKֽxW3t$rEܬJgg$fQj:e>>n K"_U58r0 dž nTbd,iЄKMQ1v%BAhe`q{A YAMbYxe܉<`y ΈH]6Qeh tS)b,u!$PVU!i3p8|F ݯY%$aۖ 'o#=sՖU><P oB;Y*ntlAg`B 1RqsSO>打hz]|ůz s陖 UƠ̺Mc[X^ւe`oU  ~= ,bRUE@|si]T.ݵK1e\5Pt9E@%_;PFV< U)-O($dHЍgVQorv5zeY es-c9O> o)6,tx<52=! gOY<BviN19ڵ|[O⑔3C&30;i&?{|LpH#CT[ ŋs룸E<VY:qZR92b\#T^MYFw\dJ-ͥXFjId1~d;(ϝ?oS<7Skr7Ceg   B`mOLsSWo5`EH~ӟ+<|_.F|B': YCQ0'tpjs,_g|烾I!<"Ac^!P̛ES+ E@%>Z8N_sϰ[K9'⎌=$%8䋍^BJrO .(~(c#4}Ot$Y܏Y^D |Z|l`G+?r9qq{\y Qe(#)|kRHhr]'_dYfIܿt Q+,͹O\ɡND Q"[bvvvx”i k RY!r30<17 ԗ;Ioz:BQBnӑ5;gK?ǂ{͍w;o77|.,fcEI<ŒT T7f](MEik, @LM#ehu W=θDGqY-  uHՀIpK@f?_wVqJ  $`><gɦ4/JcD\0d^D]6@3alV& ξԶrGZ.N*$@Fh D"PY D"@jO,3%D"@Y DΟ]1RsgVXo+OR]B :.5GOqؓWY%K֒h"PYDTA5)S-U AEIY2[?  nU_V1 &QaoR$_NAxƆYF0@_Tqh(0jD"PoQAlB)5[P)((3qlvPAʹoPɅ9 J4 MQ=5&@F8"@,*)%8h/h%!"qg{b.#Ds"_<3dqj*ifh\ETVߵHg̠.Y>뚋!^`Ae41F cӼDTbd,9UH(JRIMBA9V84ŐD?SAB $Jq' .4%"<"RMKeS=x} j5x=c1UT*b+]̛bzUS7"Pcda(#D_믗s陖Q$Ux`}l \I˩ @X& !u*cٚļ#`:,lVAhhN5*>N."q843ǎ+Ra?{ vCB5*n1"Ν| a">x(7"3*Lȩ٭.3",C9JbkD hKl2а*'Y*A_lTI/0xP`r;#$ႇQ n &RaD$dBwxE8w%dzUeMx(| xara_/;u˜ <I y." vWF7saY:n UV$Q0ˋhf%{>l`G8? "3o<2 #( O1:4 g:=Ɩ_*.nD$uY0{J'iDTI2c{;pםW^oE]T[ ;`^ENV(tlκU6F)sԝ%@>  hyb~YqX ǥ {JCKdaE݈h^+q<.f )>bLfCD0nZ@0N(yve @FP9 D; -_.}g#]TUR:"@@PWpݼ#n-W_9<:fv&:j0Tba︶m\z;qɫRC'~pnpdžϡO=vWylUÛ@ kr4‡O+2<h^W#oڂa/!H+K_Bkb~(vZwnEir,"Ӛ@J,_᭛61 /~~sd ׮^{/'vnڛG?|)[h[g.!.,sfjF ,[_{5v%` *0'eU,lT,H*I+Lse8lOûjg0 0VkQDe@UiBu⇌\kX.Py*-o#^}W {&5;%u}d4z9\,#D G ?HD ԄyJl,OLN+jzlAͬjl6sҤa*0ogRJpNj?m&ͨ(sp3O"oAB89ϲy[ߧr%'!L04hMÇ%c>NT ؇8Y32h-1 R>h1 U# xgp]`fhEV iX^U*Bj I0gb.\c󫸮8f$/+)<'"P= G!#a">o~3/[eLs@}M Z$9D! ̋+lJx0e'_I%*fXLƈTȢ%P*]AQ≂a\U 9[ǂ&Q 1Pi26UefvV@}@ P]#%D. d`__lٶ>mk]?%1 xomfG#Ju#SX1ʋ@I4Q+ޥ:Y~cO!AT%/0W3I1KWPQ&YU,PjmlԵEI$"l#(ۦwAȃhQO} gn QiZ#$YćQ\4"`6//gz 끬 ]Q״VY"\e)<O9@i=92b_<08%(PɔZl "PY!D9#\xkkkUhxBxYhXŔQg;r6KY<(0CIoQ V}@CC!6Z kLUI<y碂!DW)mcg8A/E]R. Lx'l 06>MMږ={=Cr (cP0egxD?ҟ܅iV$Q)1HQ@=(60ʏ\No8p+o?ج!2=tṖ)(Gō:d Djms<$2* "T`EҀ `9J~haM0vO06R]!jI aV#J¨-OV1aT"Ќ08Q܆Sdx;IV&PK C?ȶFiYt'MNĨ; 8KM%u Seqgݎ3U ~D|QYHv!Y޹LX|%F?C׍7*DJFI2|sc{;pםW 'D"K~5Ko|K.Н]|[J7  DN PyĈ':2uEOLGZ +}mv=W~|_{_#P9SQVh84?>S_;}[]Cl'|\hD"@\yZ}[È d_C*8~vK,#<ʯS?VCY4/>~[ oY_ p Mݓ}2Z Dޱ+?=}e.YS7"@ CLD׉N~06Þ.\SXNwa|5M>]`@r_=]]i}QZC7qubc_hftDžVJFRՅ`i71V==gFd(b6_b n֪eiW'IBV -X;-}GYZbņju$s0UF7 > h`8[mpjy#yRCIקQ(vrF@-8p̙3K._/_}Ÿ'+ TIqTVEjc K(L{hذ,3ZFW? 8FI@hE~%/1 .ܤCkXmͮKߝ,S+牢% _G~aT "Do /P#iW|?K. 6۾&UOůS%NXr( zCI~:]DjX0hZ?^WRAS} dٽxnJ *|;q"hruNi Lx KAd11w}Jmh8 eػwoF!I h/F)s؅dFO bbTLkɋ|d ?HO;X. r*ofu]M9J-8^ˢF ]DZ2~΅NPՇ _CK_=,^mM`m,l?S~Y~?Z3D"Bz UUdڿeW*$v[6S($=E#|%2O}˚'J`g;}GΦ>D&fJb Mf]i?'[3pa8!5gl<dZ[)an CL._ $-@£/>P, igӗG'vb[j\ݹ4ρ` .̽̅œ`_QWO.* 5$r]*%] jRp.U8&<>*rN."P5Q"G|V=FMۊrOfCGnm9+ǎ۴iq BS3>½=WgٰƱGMbAȦJ7O>NsʷY?8r`p'άO@vsD 9^e#&EQwK."P=Fs4INdG뒦R!D PԼRi4 x=_tG}=ޗB'W0]iO=Y s]ਘ^ =%fs ӌ>'|1͟VTOS5myS&2}O>{^gN&LmH 5O:%. (bΣ4NF>fn?Y%:,L{G;'obxm4^ucD݉=3 Kjbhr!>ܿ j >ނdR4gݸھ s|fY,DI,``؁\r%KVF6@,X7|.j$w*L$f}N۩vUxކ#sCeRvY Qg\iԟT jDzhy8K/F\q)3b!?3"PqvbntbF%D] &c.b ;FPbq8I>0nzR"@7{G~W\f&Ch69 Ov6Ώ|P7"М*0؋g\ٜ"@hTN~"0Z~"@ D^0R}^/I. D"Ђ*0TS<ߚSF qR)b"MQZ)8NkE/`)+"bsB4[eiU+ `J1|aD`('#82MdzԡTbaH^}5幏vtDžK<=!r`P%2 Xά Bq%[o,kɾ4.kHe ؕ W /0h}엥O,O6lfLX]tTba}5{nE*[xE ppa4/$pMX͡فKW?7+ F\͎;Hxk2"c$c$ ǔ PAH u%ÅYaP|6<Gb g~2*8C yBxDD$BVet>n)eejM&FˆMSi( &EIYb=_YdNKR]?Q$h0p4@UW\Q;ݽ0(J0fdJ4.6bY0%h@7- \)ސUԡ0U$%P#:b"uRDžQ5-*7irmN&ǩL:RySlX= Taa\퉅VEF0 Y.7l E'ȴ%4_Ne +KYc]c`]ԟIZ SGg%<B2pOZTKt(d"cUjcŠ^W."P- ?~o|ϊ "@ 1/p$uߐ_!ۏiÈʆo䓪161#dtQ˛1oOUVw(OB&zJ-$ .qy.:5s>/R"PgGyG.µ*4!lV,/߇!6|`{ *g,`ɍIn@N[$Јi,bjEU#& XxAx H<CAF۔klaerW TD  ۯfAD<{Y^^>zn+1bNWp}Nb_agyya`# a ?amUI!gc0#C^GGE ^pjcXMe.K H-0{~{aGD @`}ݘW߶ugv>W]?{?knwy,nSb0=jgEmI22mӭ6'fۙd=L3J|D"ЄYEjB+V/u=kq4rXIxe;.6t,LiDS@#VC ׺iJ4౟ͣp|O~¨tUA] 9C D&+$_ s]}fOw|䪷Aү7_|nqٯ¤x~SO=%+ .o?_O%˧ϵ/jQ-Yd`޻\\?Oi|d O͈ݗ*4P|$s`~9/2<]KY >{ƣ{2 DNŇk+|&xo~#]`4<ڵ_v2+?|\>_˔W`|}&29 -Dy#b WyQ$%D6!,Ʀ\bKނ qgf[^๐mڄ/_}8D3B D"P>f0ogRJ͟Ua-PYAxr}˥MsΏ8m?Yz|44vt8tukgH?bi%ʴBk`rOY15ha*:_&'4 ˪ٴ8J1*kQ\Կ4!udϦ[.賗i>o~PJ@Hw,pQ^>39@$p3g[q viWxR$wn4P^M*@{Qd%o_,ӂqkEZigb19Qw UT$:q%o)9*<q,>[-{w{펟D#$cr,ڐ$K@X!%5&2[ay"Xt7 Vx.NW774Ah{ n<"O9FAS<!1# GCuFQ@b8+Zqn)Ti݈A,J@ 0Fl2W!k9UB/U-cJI('w8TK3ҰM5-0֐bDTNA9x2Jh d?+x`AI*Sf,ͪ/ƥܟByx  5W<!BP$ @AC+a 9*ogv/isB4ꤓI(MG0^NT Z>h[_|믿^lyvw̠i~9ׁ5հr)cn̋Gjj< "VˋXjhB UL:dy>iQ3Vmh6T&p*(l[ vO%cǎmڴT$D90fB 4'[g0|r*NH0Z{@ZYiDpk^p$NkQt\ph] Ģ,5>ͽ r=FL0xAx 0 -$Pb"(o͍!T'Ph";L$޲쿯]}^zoHKjU OU/CW}+@m;F1omWA. l9@B?,IDL'UgYKBl|Gaup9v_<2 &<*Ddh 8`볺 +q䊖4 ٓB![uvr[ Hxz'sP]/2x+HZ&TLh8_ yJm1f'QcEV2'XӻaO}C . k&p]Qjnr]RvG5o[pr}`Iد[éy!|T6rd+L[xt,){| ؝dX<\1kp+^f 殏d0g*d^պ~aSCܤhF$ ڴwü]v)Y1a#.ii)$ ^Fs8W4=Y"2+<ՐsLhE002oܲN'eAҶ ۗi?*@.r>L~+`c.Dh640~=:%i4hNC6D$!DImc:<#Dfr̓t[oC]Y%WR`fI?Dn>1 w,A7sq(;|vaJ[AQToO`of~z2ӓ7 p{;f^eixvB[C `*4=eՅ/0e^{0*m?>׾L!|T)~~)c5DSz(F0_tv !'ti</k0*Q?<Ch{-O_ SJM^~\7`[ 2< ':RpD,Sd8Nj_ l24/'T*<Ba#=dhGaQ<(WJ! &H=M/AǮ/+H6 D 05`Cܵ^@߀oJ'K|•QRt<<RΘ}rq4{<H? :Hr gƬfU[YSF"@@ M%J2L]61C>˽Ck Bb`"5@7րq<|AL# ea4dZ:Mi47k o @<$āF,1n&D|bagEbآm'#Aۛ"6!jvqYz \Q3myzbc*sWd_q0O%&ڡ'(i3gJFD"e$d5AS1WyEE\!;3q\cOG^@ > ׏S# `9vu> 9%vuk! ?om Xn^h,othJh-27%YKhJ6-f?ibLD{6@s,ߌkf"֊9/km%ެ%3[) `Ur :$r;`m${KǯK#gƘ;znx*Rrn(cRx[viPPVOOM%b QuzjݙH 6NG((WCOJpa8!KME6܇)Rk+.|P%Ogw8#uW*hxo枨XS$ُ>ҥ`^p,ݽ;q% yC/I'~7$o8Q"G|n@Iޘd~Gvc<e!ii95~W3c ȳ(OK-v@H3z T!n \;/}zCJ²+le;\ ܢER8bvr.~YfrvBI~+=۝PQuzXp{ޟ)Z P RNzKڙ%& ρԗc.0)Z,/,ً^>$9 =qwȻOQԙH4}pX2X%)b~GD.| ?!R!l5:d XM^bŸ?}cީzymVLO no;EZ 0ZND (v d]v\ʜq!Č'+ }!0Z饾ʨLw]DJ "mӜfᠫmT lWsR.,EvGda&pf>Q(PJ- !NC?H,u9!&Mcb~(IbɜT8RPLl  K@-K% vwӃ#eDZ0_аw4emRO,J nryo)ejG݉@!Mgah%E"PGzz*"!@Lف\W,qx08U!vGQݲ< ]mWOq#=0O\}3e=5I"ѭI< B`/In yH Py-t~3 57{߁# "6yuZm06_JZ Pg ndw5\b"yіCpO, SO"@@G,񥺞90RmiZY 4᥈` + D"g8iqhv"@ D,baKPUavu3 D$,;tB~S~RH)"@ h. ͩ/ DPwDRS%XO.(pvԧJ#JM4)=i #\UjL_YBQ+S1D(}ST0nZhE"uK β &UuI(KxOR@O BNZz"?SJگZ/CeTxa6lf2C͍ԧ4KQD x`C4H@jJ%4fcRƐg?0b~X&+qm͢IJ, (=Me8v&D10/>f"ӹF#ۼ#@_Ly$p\c]B@/i O[zH0&sAFˆMXr^6)Z@0 دQ}T7Lì%7wl0=y@W\Qrh(x7сY^1!$ OPc JRI"fdJ4 ƥܟByvg7d/ 0 (J0{+f0*i%!GPY/_cRl"1ӊll0 F xARL 4OjDC 7 Yvm}l?b42 xTF! n˫ܥsd. 3Ik|AZ#謄PEbhU`.uL_1FT i+^M+Q98o p񏰅VC"3/JB ~/+,fZAc@aD}eLj9deeí3P^T%b=]e(L]ەYzgi]D9rG N??W(Hu4#Z Iβ_d|[8 R%\>v9!ҭ|>ZBm?{ T^mH,# _?_iݓ!j9QMdVƇ|?ڼ7^,o7[ϏX]}pڑpIXX={=Cۊ f$4( 6f!L"xR,rPSLGY8NR _gpi0%yy0\%%<*_B^]$,?1vZ0z,0BS(};@[Ƴ~sgc*9j`>*71WpA28tO6uׯo=g>l=XfyǁsY/F}`^CkO71<.nu Oʘ*̈́F η0$HÄHC.|/)ؒI޼Sg5e[0wh9+uw$}ۏ1=ϩ?77Y.'s UxWLpC䌑ϕKY%ϪPp$0FTFZk~Y'pqSDXctv0/^+~fܩO~-/÷~_C=D9~1veLa@_/XV],{B)pw)`s,xۣE8m':aC/]ҕ>us 18]GuohZXOAח1ߊ.ڡD6 |3K ԍ8:QBNnn&!-C-z;,Os>~fO顓S o±#K?cOy.6G[V|}x'MuaFx6cR;|&(A(Ysb9x4DKgyQO&*߿Lb<d0[eB\,;.$u+dW<NU=|={g~fog>̋eD??Vj8L#bx"qkA[amv)~u |BG2M"@Z@;[ϻDDڼcRtԽow#߱=yh? ׳~"WT@EY<*}q2X]N}10F@yaN jȲ߼3E= K1^7Ӕ׹1Xl56kfkDW?^gGRȍIՕSŇ_1ŷr~Q?^ꏔ(l:MA[[W9 Q_"@@o5?;~#4X f;Õ_57Y]fChbZɤ|,ajCf0;sO sN׫+׿ u"@:@;[3ov]OEdBηһ wgOC褌K?Ov9s.8^on1WXI~5Fmb2U5'evRV k~wTw~7X%Zp+=oyv_oa<(C6t4Z4 B- IlJoݪNM'0xq&d|E:n< WӯUbHoϼ+8SF 9(OB@7ؕj421:T8"rZ$MO-,ӢE!Lb5ْtak/Glg6eal4ul<oaocB @}Q}sT'f~ce0D*8WVpE,&Kd)#o:]FPn>}z$iԊ: 1wވ^B.ALf-wiȉḅVaIHL*xe ?ÎH z!6 60ve~OdBk!d#]'JLŞC@e{kt"wQm苾υXFL$Ͳ(YxrĂ$\y91&2+⿅p$Zu a8YqRE/8߬-|Vc + Xnx1vuNCǺ;6 %kܭh4F¨ȎfaS,PnfH1A4^\㳶~I??c#@''г$.Q-<1#-# e)]D%(aG#>!q!0m~B vxr.~YfrDb:f5򃀆7lL7ܐ9hΘ-Ewv[+ w5β {QO̤Thm[n AuL,T}шfqi0gn6aî+bJ$>۔ :3ydNm9L^I!Ӣl76C[OvTVavhzhJ!D,/Nĉ>%4= x>OK_O gѭ. bҥR}Č'+*U.2~)\B+j9Ԫmd>q&LJ &@FtD( s=\R+Cͧ=BZIέNKl7^=43Zɼi|7>dag"P&t&O'ڙ׃#e t^@>d+c?̋qȔҶV 1b|<_= B*y UT\Nm2巢sH/P $cc 4*pى@x6̾`A `=Qvȣ*sYKf!bH `RȌ9]? BBH-ˣeI l_Oy<6řLQ*6 V{z[}}IÍY*q*4KX_eko7|eu޶u>;~(-ό]wH ' 앚kN0uQj> l&aj鐔I܀OS"@!w3]88EYQ&&\F"ՈX⧐c4;|U5ZJ#S-f0*-U- O DԊ@Yp.,jHC D4@YPz)"@@4+jl$"@h f0|&ЊV|ys5%s n!e?ڱWjV[DOiQ0YhZK&ԭC!7Iڍ2qJrO2?Ȳ w,5`h8<f*0ӎS -G5!';>Q4_eq0 ` C` eKGh. ؎H≀@8~ `(^tُ9CH$v~^/;"IcPr`€SeF(Ǔ>D0/>\xInQ!-pBk9?90gJNׂ5A4/y-vS<PD;'e&ypR /]'>j`%ψ#zdG0pq`A uN@KW\QH[,u6?czThV$[[C^X\"P#DBkCSY'ńNGY 8ݱt/,geb%GbTñ6R꒼ꫠîo:hn"ЦO1V~*۬.a^Ȳۿ۷v[ۋ > /RFdwR ёp=kX_m_c f"\lv*3;[޵L-kaSlWVjYn' @z|rH{ 2=KG)3l6<2E5D/NMʇQI Dy$a苟iA?ndn\TZOaGj ~ lנwڿ3sEu/zv cv=F/ 8綶 'lЏT)?@E{kVO?}Я)heRl4|*J2y|a->k!$, /G}&4!bBrr䌶 +jyF4MU|c^v0F) G.)@}HrЇ7lIXcJ={,//=zU0D's71ʣP3 a̸'afLIfa76:A>w./nIA=X/'6V%|\QҮXvW3 9sYplE $C*U='oϓz_/L@ è!Ǝų=L$X>%aԃj[ʬЇ,$z-d_lK,("@@G|qpDZɽ: !P!ҤD"Fˏaԩ @#NJFZ4~HH3j-V~Fh D"`!PqWcldӦ=x D"#PqM#,GD']D"@0`$D"@ D"~r|j&_J}ԅG {'VN ciˆY%Ѿoj6[PrEK@oB$f4Z5b>g;瑺FF%oK ԭ¨+^N@*Un%n{V_H/K.O7>DiJ7Qx>揿;_bеbȒk/"\G{_ o ;j[Ǘ5O(Q;fuB[pVk=Wv6?Z= DjpI ~p6B TuD&XWN9_]z7EQ ?/Ν ]G=J*x4)*ռ*9j<;O?a/QmɤY+LϿ,O]wlOg٩feߍ|5*+pc[-q Ѭp@'ur7GC ˦z2Wf9*V6n(5oV:0+</ t {~Q'+؞:1pNwK9#U_Xma|Q֭]'Mf5t(s0f0@CcV K7/I%D4@\~5OG##vtP+u#}R? a#<} 6'1 8en o7ќs%zy%dGW ־CHԜ$85 wO~7i{ d<=2T8əSvS';hX:ulNeJ z6ҟ7 kCoOVm݄2a#Y,* g ~h+1޵t3kkܒ~]˟I7X9ި=˛ڮ\|ZIŚ֞RT [yS1 @װ1#\}'[cO}ZV/א }`h a4D"@jJ=Zja.$kϘ V3)]I8 ף0U4=N`HEHZAC}KlFK8+rRV~Q>Pϲ Q62@-?ͯsi9+bw [Rѽ:ʍ xx( O] ؊脑Q!ŋG 2`ɣ ni\C"Ƥ _׼q`-9`:bZFq 9Ѱ: N`I, -K,,G3ahyQ ܜ tﲀfJ|&$H(=ž8abBy<+,~ʋ8gYy4 kH XIz% g'`>Nc2sX9gQ ь&!DbpX[/ٶmk.Mpv>m^^<՟y/If7Ff" Fuh4 D?&.gNNS$%Ӏ <I Ds @ {eZ&$80B DԞYgJ D03@ڒWmJ"D,V[+ DV!@F)ғ38{OcOSTeDRVN/j$7W)"A<.|e* e6hץ.@7/"[cI&,PRN&@F'}Z;h H-LG,Sf|uy! 4!&adTFlH*wRUܤ"qYlTEY<ĺ/asP&VeyJ \gX ,ũ/#@} ;p88NϿaMJ1^(.xB믫L,řmJ2MXd ϑ-p(,y|Ik} ʔ[CA`Z}\",4YhCФB,VS'(@3%zyqگDU{0TFv0EXW.1Q\/]y}R`"/Z*@fq&<ՈfdB7]=*6QzP0e]4 *N=Gb9 K f4T93K >Dԑ0/bsVa8/W kIhxX ˣ IFdz7KLLcҽZX4@TBL,GU1ex<(B%+d*6G!蟘e *2KJ`?5ż)0'Dw0:fR@ >ۊ\l"Qą7pZ~u#,`w/2>8fw2Z{S":'lբ2#C8l½li_oLsf :Cs#&yo4Dӵ8_&O@ 5/LQ '=< (&*FyH =X~?0 GK49S9Rs<i6pYɽyʀt KY M~.)0Ҳ8r#<rW!uDa/߭=eNXa)F.キ"=/-nF 08jg4R@< OR2y<ȼK(϶ZTԠBR:03@@ ٳgyyѣ?ԯn1 4qf<O~e#K> taaU"!8ӛv}% 6S70gS;p;+oM]nFO1XS@,ٚn ˌrl@?qd!MD3Ylj7Q"PD(s$%@6+k mfIXz~wc{;pםohb'b[ʐR-R Q#R1(@cے0Ңha~91ˀ)KcYڛY}iuDTbTu$h ͷES_+ICY D"@jO,3%D"@Y D"@jO,3%D"@Y D ?ލZ2N?\ #e7P>vy$i bѷy"QS69#1Z-t&0:Ӫ۞@3WΜ9S|zzj'31(9GIMf$veՑڈJJ0;>~=$ ?n?3׮$*q`6pyxU'@FhJo /P7LȻOjH믫Y|$KMz6x.&y#2+6FrrAo(+EjG,ڱ$IDԔ޽{g/v"H<axJ.jNzNܹ)P!FgfbZK^FI#yFb}"at :9q"KޞEG[^^ pK,  'Pȸ\+UH=I1pr2tYRaBߋD%Rn,ޝÃX 66Ծ/c;xf_'͇G郻XF*mV٢a%Af>el<Q֖=ޗ2Ω4c ]$)/_w^\"F$yԯ=1.+j;#,㩵s(xl} pœ`_ 9Z .rK|.BX$X&eT۲%b:p,y/%D Y Dy ;vlӦMA탁sS;1 K(L6Wg0 M}>oQ!I D˲čOӻŹ;uf,0X<lQupxwjCD٨R2e<JLkkqgHaOk'MMy'ʹSSF:~MϤD36r+#}cpY~ECdW,{cƼ8fR]Q19)\],1# xKff|pa>fKDhwxL p Fyr Bߩky7XZR*ԟR) є"h]p:0xr001͉;',噌0D~<|/W3r0;<U?sOhgQMw\hs:}LK ʘ1 >0 yVOqqHF3- [ Xc'}h4HK$D4-W s[yo-=w?=knwy{.7߼袋V=إ23QNzbPjv:=ڂnV2Ip-4)f6/0!r<q#NjY-uv0:ӊ8B +=b(Ɨ]=Mqzii ԣZ%A"6$u#@Q'$"@@G o?-"@@Q'$"@@G o?-4-׍*'M4^O ю?bj,"0Wb?NFC I\U(kfSs> ;ũŠ /-Ldat}Uf'p"ky]x xVE?ޭ71WbME#xxɓ[B0+d08 nRjӠ{ h%CYx f'W9 datͦ"o+^rs}LF$?%Q`PZ}eZH":YwiDE(nZp`lbF(q殘?1xFF0k}x#賘įPsCx5s-!/j;o#ɵ2lLAl}嗵yg_^,tQ6D@@CwzgYBP}L/] a˭ԡE9KE\#wT($0mVb~h鈟#nT-dIyJh q 5>?G;Șc+X-uүy Ѽ4#D\|ůz1XD+LR.?O/wYzL9 U/SbiEbƓؕvIBX ֬a14N Ϛ5,GV'D-ˤTQh[L $-LxR &gx"TZ L=bUI^=? 3ֿ3?HQRa6ًBN0@@pk^3?4y?_( F׃#X`9KeEǓ̯e<T ٴ ̟`F^jץ .'mF*ǐS>9] x$3 љVM\i&SRQp !sDCPiDP@dzȥ@1$}bieEi*PzyiW,+I,iGK;=ÐѢq?I]bRP" !@"д_1t[[?WHm[7oΧ;Xzާ~w,x}]o737s⬕b=fQ+$62/ޫļ3u1 ٣N;YqiD u &=]:'@Fh D"PYD"@@( D"@J !z"@(Y3D4 V ȕB=dq\Yłb(SH[sʦӖ`lW4)PkiixekQ-A,M$ 'Lc2,مXkL,W6Z]1ZLu< ˥4݂egpDFI%$OTdͿ-İaQu."H, `"м</(PzpdM mF<ϻK߁x)^1{a71mQ> %44k,0˛f#D50/>\;}I\^ T 4 b`"?H<4u,s"0~8;S @1RhnSXܘo`%9\aɹ߲r򲨁B >D jW\QLq\ThCBg>8czQThm[n rA j5KKͪr!ca.j"5 e] u@鈟[#hnveytQr\;"N  MG0/d(Ǜ^cPKt<"g`\/ s( yssygVǕ{S s8c7 ӓJ̠ R6#:)WA‡2gN##0Aڒ@ ;1ܚ෿\B|{{PLS. |ւocr'ˋ|xʜ+OR1n7*z"v ;Z{w* +ږhQ z48r#<rW xa0K,H%NX#]6zpĝ8pC໼:y]Ż͝D`sy$k!.9RoļHX<mC?zuSkr@;ԫ7HZ={=C bQEL[@}޵alC@=NГ4۰/9e!Ϩ,d܇N8%C$\[ +ηzSߵHb] Χ>Y[ ]DN2( >Dy b(~۶n6ޚO?w,=?O]w޼+B3g{A2[h(_P,^<u,D[0Z֑D\j]0-=¹u0Z펑D j| N*ܲ&[~'@F"R2 Gl}ejD݉@' :"@@ Qo$"@@' :"@@ Qo$"~rDm kRU£}IGJ` *}S \"."% +2coq s(4 VQBJ,%D4bjXUVfgxq<%uQ]Pwɭ@Ɂ&G?-[&<! w'K[l*VLYrE+xrXqqEzshXgbeꠟ}Bk1|P`}H|da'";`Uk'"^`_]> 3L%{mN\`}eWܩD?j4I)$@} *ǣ#}xф# ‘` ˁ-}FMic.O98_ϤJd]d ,u#; J%x.V}`% H/竳]Nou`=+wnI/B6u/0˗":Rzg1lDvx<>'Ohs!`S_ow߬GsJrs+#/$;:K9_whv}0<59 NwD17|'&Pe;!-v]І@ͩLS[3ޚVG{.[$$£1g䋁3 1b藖!> '!"-cyYnpi.ڷgk9aeҚВ|!dT c7s2xD-v]hyoGK=7Y$D PK6~3kH<c+wfT3SP<gl ٖr3*;#boqgj.枮\d1Sd ,Ye#D9YǼZa8D~(7&-|$<u1x?*R%D$E$<Vbb Xbh|KAb^J@r)-< @ʅM9b ]ARUhp Qs$'?zÙ0D% . Q@Fxt%0\Yؓl2.Ľ>Q`#@Kr-verNJwdq2݆EXumزL[ X_^0m\|Gc3XpuEÈs u֏n=fuk~3:~44)niREI#L]qqZْi@m Q[$"й .IY?-+ksF,4? Dv$@F;UZ D&@Fԃaԃ*$DdaC"@ "D2")҈bkeJ$eTio1d7pc6eOߔU"*ڪɊWB|u9I)PtZ@N,I_d8Rlda"<|if9*]Mf,((7N)%US*%H0\]Qv^X$ɩ>EcA}z?gĐ%HaDXyhDJ%x"zYb%{Ń^cI<e837fޚ̲:X `Sy":N4K2cRa} *[CA% ^.$X[BhD*$Çw7oha_!CWFegr# +`xMCȂ>&O)E$)qR`pwI`ϰ묽8b 63X06K!^<ָKmT$RΔԷ w#I@W\qEKY<*K0-.|${X If3 7 mĴ?}0U$%"x|HVIUg(.ۤ8|z7K@_녔,x.|2NJveZtCX]=X;CY` 'fY£ʲ̒(oL8M-]̛b+n*hH mE0/qU` $F\PS<r* (:+uXY^Epo?6o+$M vOEƜ"i6\Zgwpԙw +XIi@h~Y/Cfx`> Q8Spބ{x>BQJD"@@YsNkvy1(ߢ.Kf`8fRseԖP{(5b U6ȩٍ[0#\f4 JZY-~I}"^9#\xkkkUr}Z_6pp3~:Ct'I(F@}R K 3wRsIj/&Tap`S-E6`%%X,1_/c,BCLW n2-={,//=zumVE}%!x0G*NI搗/Z s8&$12$Z4DfYI$X8N:vQ2=Am<f^ ۻ;\8C=y̨ -\ 3 .C BMljADbf4ҕWe+m[7oΧ~QKɱ^sہLb[ʐYJWQd4  n@jMʒԚh˸S M%qFj@s5YM"@6VxEUGV|`8 i9da-#pC"PGda.&D"б[O 'D"PGda.&D"б[O 'K@=1"@3I ePOON; :e[2_b DlV@[`ƪ I<B@(KBLLH4W yiB@# K(jLU]>)vޕ._/_ZXŸ'+ 4b=%&cAacL{h0`퓇jB$̝3G9=C? MH!@pY+(n8Oq& O,?x̥:{D8(%NhVEQIR~U B:9n(OF zCIQ%@F{Z9hWvZ ~B{W\J²k_ C(G[FN!lWbt 1j* Q\p}m$'"FO1]0vx-2QӾmu7boAq{}//)VԵjw%D(4k^%~&n| ɠFQ12  O鷼 tBb99BRŃcFu4PN}, Oj_Ob籝zɹw]ۺw֣Y5gFYWe3 5ph-ueEL"CdmKthDZ"rO Q6;3x)XWVf;3i`3O;s_Ovb~ŇDKeΈ }.\r.J~,,Hޘp2,pblɜ7؝t^^ִTkqda $#<ӥyag>ã M =jڢY3 ? ]fEbˁ: n/#P7t<SCG^y"n"2"{ s%󒷧K1Wgda0'D!9#\xkkkUhZĔ5xU7@KQXu0 .`y ڭk8*&' wbap\24ϝL1͟ILbN} xh;Ź/ˢX[{jm 3y/ssEKmIYxWH'"@%gϞGPn6g!;{2wŨ'tnuzΉ( y 0rF޻D.m[ (ӻLRw\_1"hs:},0B9-s̀ļ(L"?YHD;^p.S\Π} -~[P&j(Bۃj{VAڒ+ƺZ㶭fӳ}s7]wޖКQ]enK_fn(fK5.sH#lzE0nD!HF\qpXiЬ4M iD@ЎȄxhq l .!u/MO発QԑYuK fblt cCӤD"@ڜYm~iyD"@6Y&%&БGn*'DdaC"`R߯TÿGG4ɖnPl?8seu*Uy?A툔SyHhFyjiF@!3fWTTuUUXԮ  O D`  ˝.c̼v`cBեuFZ?!*Un%n{V_+[ohh_ƕ~ E6ԃU?`^F>0h+c&ۛ@AQA "@@ݒ^Ӡh ;h) 7\¢WIp 8w*8basv:̢-5`IkuB0ҺhG~iynm >|p|NŮ^xaU3)>س9>"l+b:] XGZ3XbQ FAvɎGG8\Ara m9}j77=\<n&rifjYn(Q"@{<:NP1#p#<$K*Fo~f/X]9MR? 0A2x64) ~߬)Z7J'I޺,a6W~ۓ d-Թjlv#0ЩȘ2L!_G p\G'z'vlNe _rD, \"@*%&sN{qZ#5c珳-cą6/o/cbI큷6b ? 1?qk_dFM$C?(,TPrո[@ 5:s )k$틦+y^{fuvz8Ď| oFr2O, D"@!\^anQj9c-01*MӊTeL#T!f/[$Ǔ'sAuzju| 9K,)?j<A[=s<\r0YY DTJ\,.#ڵ9Bm~Ip ܀jz,.vcxG$ jڵA{kwnYhUA=`8h>_].B)1y4`E%DŽ}3_ha=55Orsd}}ǹ[]MU;daԎ%I"D h1k o<Bɞe?z<Ù܇}I. y  A67+Q+2=ZB Ow 4{ NyþPmupXoIЄVdQ8Q,̾$ ĤXwG9 VN \좦!!K`}Ch۶}Χg]˒?^sۛwY`¦~{\i+UU T s?wR7uL>`%D"P#u=ԨGވ FKP1dat荧e7JsVqHκ>a,dvՆ, MA?nuM,4? Dv$@F;UZ D&@Fԃ%bԃ*$DdaC"\ X$ҋ9`E`TPݐQ7$"Q^ckDzy9.[ᔔc VF!oyh{F"!\fjg_oq%r*r$B/uU$lC>%iY,| <B ;nj ?/`XbNCkkL7kv,v"`0I|Lu'6GLTP xv묤^ZR3C 3Zl긑c-x4~daC"@ £#}oq$xvUͤx #ZZ\+i K 6#e\[;oX6jAc8-j %_!X;Ʌ,9,|QRQ&+ЍX#A"@@Rzg18ڈ숇]C _7{E_0(Je\ԏ<( MrC\7+Iʮ;$zy'dXmqGޤ(q. +hmO&5:H.LG4> ;"c[Lc+ Vݪd8<1,ʹH"@Ig2D!5T4ۿ4nbIomE~hNjq?u=>OTDA2²Ѳ&sjyP ЭzԌjJs/݋鰞dat "P7G8f? rz>~yf$ :<R2FBhsi­y.W}4 (^.0h\OmMDFD0-n4t=j)fJqԇ,2Qw"@@!P׋Un!:b*F{؛>xG<` cp$:tkwnY{ULڠ/_N.? h3%&&8Ĝ@ f@hZ$bmrtC,rhQ_"@@`e92\R11$atCnJZ'+<"C82ti mN6qq]ry4⧼UL{|_}W!Ò57`I} ",D4W mۚ~5;N<e%n 57{߁L Փ&lg\yj :׫phC/:f[چrr|vGH"@ɻ]nɩSy#oՏ@Œ¨ $Dz%ND&rf0QMAFSZ Dl8ŜZ V$I D"#@} D LI" D"@},H l?Jy;B.OYYQ.1ˆЖM)-@n\m*i UOgFI9+S90,&+ I0Ad"Y< RWjt,<G,T%[^Rꎝɠ(AkG;H<էs 2XERQa^o-ecn 磂%HR $pf~هi D.<PRt |Bb%;u'%I̘]d ?5ey8Ƕ:7r 35aI0ZRda "8|pYjF%0X؁Ѳ{:'82*8C <FC{G),8 \cT"2"p\d 7LVWUL rc/Ls]LnKZ*ԕՇYJR ¼+̿:>eĕE}?SG=,S,<ah&eNOwhf5`8e?HSR!u%/9XFDlVІenԵst]̛bZԺNON,# ü7iOfIP6Kh/VYؼK<VVgX +:%X,qr G $)siM+ŅHr$Ȱy98 Sc(v3vD:{<qR:TGށb']vf Xp0D70 3GF̑r?V%x{4PGw#; ofda4!݈pKȑ#<ȅ^v_nGߞ#<O.bVnt9E]%dBwnK`%Rl-d275q3Ha9)?Rٱos$ ?~"ٳ|mVI00vL7fZt.($C!^2nXo=2䋈 UTO2,a);Z]t1N"JjWXkT6#j6Dۄ>D G`}㗵slۺxkv>xqKM7]wN[U57$y2ͺD! ]>h2Yo4{ȇQ.1O`e0xV_V7QT՜hBZ"@hGg.Ys2F@k#G+< --H[$a ij"@@y#%a1T0Qԛ&@kTԑ"@pM, ר# D"YQQG"@ D50\D5_BLPOH!驾`鼳Tua7/`,X/S'fEL:PaM/Hc%`㌢>!YLg\'$1h gf'p3gѲg00Oƃ;y%]:_^Ÿ'+ 4`2vtF|R/у,9(3Ian$Yw#F*jLUpNMTYD7x^(fdlӊ sǂC;Z:|}`s Jp(s97ĉU>v3˅>׻=7$ zCI~B;]-N,> #wbF|> /yL!p|Aww?Qω@6`B XX<XSHX@z:ۦA]z͎RC޷?˩PX΋% 7]ܦLFSR "PȀ׃|Xh`wH4}po~w%iT{qjc'`0~R* [NΥ/G_Z=`ۺ JoD?[4d@i/_u{%?OW O@ \|ůЮ]vb~y3P,] @ETƜ^E9ѾOs(ȃ2`=̽̅_O&'X`W+߅&5W8 ]6cݽT6 j40M#D ;vlӦMYI@X8ݔ=PɊ =j׀M93i?D8kb3s/wʙZhRJ{sd(5~I9K1V2/y{[rԿ¨TI@k(a^p.z0#.p3-9–Ot&y ( Hb4p9`OqR'fMj= kRv)M<)c*_[Z᷀ D)\pżz3@seL1Dw,`h<Ur!v8Oİeec+/ixx>֍bjp뤄&Eq|0@\]L겞ULێdX_~m[7oΧ?n馱^ske[Hy7/f[ @5Sr9(:273\m7]2f1ՇUC|УD&4/0v r<q#ya1m8,dl4iQ+$"P3ځvht psHH,׺NAF, n hE4#߭ԏA "@ D¨=SH DA"@ D¨=SH@3g0`%0Ze*+r$X JZ15Q0xᴼ`êPHUմ5ДsUA4 MH-- <E UI@0? %JoUzcqqT}^bd d!`\yǖ)ޖS :rQlİD\ZRv¨KD`͍BUQC95z nf?&j8_v9n$CAo(UmnT]¨$D &v?lh]1<O%^ 5] Q\yD,p$g,a' -$yʤd.i(yqJv jubkH=[Y-wHa"@jC &fYB%P^}L/E a˭ԡE!rHG!mj<f.b3qL)"lu:A8ʍtKrP<e8*[٢,[&Q8ߌhƻB:"gӗkgrw},e$@# (`<&s(gѮ@Q!!~X8?.gLxZj:ZΠ{y$k53i0E!De!6'XJ` l'}$3-29QM+ y%g{IB y iF@} >4y?S( F׃#|W `^F'_Y" Ĉcs"d/caH%z~#vɠ:zkd4-0֐bDԗl?aQl'yc*xBnCiŵt),D IL +ηzz rA\"ccQY<$w]2t&[oUzknu"4 %D2mft-=74knwy{eZѨV$ Y:E"l Q&m a43Bhq ?j1N-u"@FX"@@sG,^tF'&Z\e ld4"@(I, D"P60FF D(:"@ e ld4&ʈA G^ͶY1uEsu֫kXZoJ)B2ja:je*WS l6Om Q[$ a@( W -kvp[^RnEd& C>EcZ,l%UQo9\V!̣V2,D*CQH8 tvٺh{G"P@8~Jc_-ٱU;H<$+39-lŃ xk"N9fr'è M6UogMF1җR8|p^ 4@ߝZFT#@`DhCbTeTfq&<&?]ޟnѦY,wɢ2jCzX*SLt!1 4G[/%*[oPgda0'DyqWvu}lQ^n(fII*q?T6 ^BSF=,q$ OB Fgp"˻ڷ|1_Zd!/N?,zgq % b[$ $D5üWmO%KvZU>i`P 8ctzk aUfz/[5+bp KcUmGP < -CA tu0:ӊ@po^)ѼXQvَQSV@U"8!}RoaV]G"skbh&w1GL bz7cż0Fy{4LP@datM%6$pȑGy /\[[;ͯR> cVY"eZ]Ǚ : 8R(n)ջlTI/€e_DDv&C1}XTaLKoKW 9#={,//=zum~e#K0|)4)BD SD] DZQa\0d9d~X;Ս(v+#{ 9`yCiVihD!_1Y[?Whm[7oΧ?n馱^s0TfC$@xVJS׃0Ad"@6_V7RfR(th !i"@@@$®Q3@6nuJqm4F cӼD"@ڙY|wimD"@6YE%D"hKk#D"Q(4/ -I@=1"7_XU- }SkvBL[JaCUSk0 APA8w4KA8ƒrcd}iOg)MFR&&O2`:QԘd'<5z,43]J#Pe LUM`]O &c/cVKI,".у,9zCÎv;9ֹp_6'=U# =+|< \FФkzv},|)1J1<ȌW_7gIč,q¡69}S# >Dw'^ 4u><|(É>0iE nZ#-p7N1DU!9(r"/(;ČULQoPԛZA)7^˵r\ u(D, l"@\\eh.Th% zDROLOc\XX"fx-+PkZE郻M鈟[#(b;n񾔩Rq0Қ疯cPKt<r7;,Ր_}Q?v 57F!(!Q<_`^dybr^ObW6W3f:/Clw/-ѵX4; Cc"&1n, 5_6!32PxZ&&'D2P!ǹ/G+j>ENsd1qnў+}dS0ʀE]d9"nKtE#]|,G$w&f>VI`DŽ%(VqײCZ!U؜M<7c옭~,:`YnԢ>$@F-i,"@ڛ+QŔOwmÐ0#vI9 >9e!Ϩ,d6F5ALAU VOjWEB8'1js\szD $kv.&J`}cik -s[[zni,x}vu?c${O ^FqsC<{ yMőa6ڹrvI>Z%yD%wl Ÿ'tYDYB ccDv X\UKh]Œjہv,VS' K?_7ڼH$@FGvZ4 D: ΀I< D$@FGvZ4 D: ΀I< B@UIC2Ҽ[uUsJ b.~,F4 }Sʔ")P{ :Xj40J3D@4e<a1;PATn8HS9YQ@>Sb 2 aD- u0:vb(A ?%1u`͋j}I<$+39-ݴ0[ЎFN3eFEXhy=}Z[;0ZDԐ.W)F0R \#>S J,P#hr ʨLy$M~޻Pɛ\k?b=+(?a3&̗fj9$&¨ FB@W\f%5=c:E υҽ`jPP*T~iS!+)Cٌ38]7`LFYe(łz,0fJg%MO,E  '`\"$ qIɏ MzY>M'fvYeiEp/2/1]Q R:½li0H1\]F,\"@lܛ0Tdz +n?K**0\1Iw ga෰w+n0z,v36+ B$xB2F9=dX#0hf @F3ҁ #pȑGy /\[[;ͯTYa), -LS`)YT/Rl'" ys Hꌩ0NVpE a7K@>={,//=zumM0,ka@ػNsz& aqNh my Ukuu8z,,y2Q@bm";Nm1+fӉ tXpu-uGBe6H"I'glV4uc1i"@@ esj%l31GRj+590zD ){pSjK-H,i2 D'@F"R"@@  oL D $D"ЂhF*"К V+V8r&kAŵ\)v<Kb9%Zs%W7*Rp嬀60f*D18A<ft:Z5TET2H52IEM(<Sp#t7gX QV5aBB* @Fh DJ<E3`osaN(ëB("cl VY DTK@N+"'T@d,VxA$F,p:_ @C_ȂhB"$PԂ҇f"Z,jAv|75VLC,pYh[Fib+h v1 6o*eJ|x _sA8^||N3)!l Ǜg_-`BBa6HP ʝ@@ LI;EYd{SL[4P ¨-OF@gpY]H<?86 dk(r\ςq<f_Eg"He NRj0_Ne6Ir6P@NfoN^[6Yc(iP0ʡE} &. ^>ZROHf\(B,DyV%WY[*cw5//*7ɩ<ĘG[`&z$@F 4R& pȑGy /\[[;ͯJ-e' ʝX7M$pLd"wriCWpD$XxQֽpҀEp5 њ&D` ٳgyyѣ?ԯnQ)Ȝ"Pb$L8 }!a> 0eq/+^̱7LٛzL$؈?5:Q<g-谩f:Sh"@W k aٶu|:㖞n 57{߁8`27$0`9n),ofLfl֭ӄ$WL|Dvq٭~Y-7Qs,TaSII`m Q[$"PcIo )$eA%BƥQ㥚~=52A8S߱6\x4 ҷ'D"ФhCj"@hida# D4)0ƐZD=_qJ(QVg^ɱVp1ET8cTeȩՆBqsܴu(>jeJ3~@Q7uX0:vbh"8sLIY<vU{IՒ;~L-/U +x͞/IO6@7}InZl ^V.*G?OUF_̰@U3GЙhD /#cT^Q֊5ԉb2[;F21<J׆&(sGF+ DS8E؂؁Ѳ{:l~7<3d( k%=@`\Na!# # #J4LQ[ΕK[d(N8f4rZg$YsHS"@ڑK#BAhː3uNB)I,f#2ЌnlFX3챌PCJRIznpt~ g F$~(fI*PEHL$O.JAŸ[iZA 0Z.D5/_/D42ccwr*X8\+B[a ~lh?]^u8@ãztyNEڂ,Ork\LrG, w D>;i&SHHEjdI.|c]vsT0E 8`Ҧb 0;>үʦ=Ѥ3P1Hu=VA@K(i^X>sݸ'r0"ްwsOv 2` S!H!pT^XL\o ˝7-[N' ΀I< D .$9pd!LۀL7fZޭd) Pc *,{dL5_H="*@6i[Lkm X[?Wh1۶n6ޚO'3pMc{;pם67߼袋Z|Շø憤0SfY<ߢHYuy4i!hE"V:aSge/~( {b*[KG" n7-" ځlVQ}dʄ5 -,fxNjz"@Lq ,!7Pf&@F3ҍ"@@ UM D wt#D"Ъh;Gz"Ο?r SQ\v.M@+Q̍p*sg,iIJe#꫉=#Lfjt#V_&GeJ.<Jhbi18rnpˌnn4o>damE"8tLcZJD~UTdv8[ɲe~he͵ē@ ? &UuI˒T m3 T\[!+O6218(gX Q[V&LFR#o)1XMök(oVL8R?HLq~VM+(6(3=0#&C,2栿9xu"JJˆ&+*Zts " iC@G(Y]T J:>"0gZxYcAS8ʠSzׂ%ņMQH<@ cpݴP!<3d( cq|U?YɁQէ-JN& eo)N@[(ad@y0g82ؼ@HbU^@U F紧" " |caPLI[@%E XR:Ba6HJV) pV" KC-B!L8x e z 泀ʄj+ D".^wEFzZ8 B/~!0Y>cb,kUUמ|sӻ K >E~0%1ahA$IJgAg,T%5hUw.3CvW݉Ҁ2,2xsrרr[q$YxHg"@ڇ@"9 W: <!I4F}H*b, =ab` MKH3%M,  SKp\qޡj3HQy1o&Z6{,6"@Z@$Y<0.KyJ 8&y2M%luFLKχG| HuW\r ^4kFW|-]BkFܒs+[r`[v -o+- plڴ2'|&ǃXycaC~yuW*,а4AFY&0.G o.G&:kd!LY87.K `2"z7ۼy~ ܖX()IZ+k -b[[zni,x}֤&Z曍)D$S6ebJzx"E) Z>Y3TV616vhAj"qc^&ĞθZ*c8!fVe cYJ2 O@;P5-%? ҄ QQ$">?n3ÿoo h@Z"@h/da"@hda4} - D0~jh>*# yGƾӕǪ'FI?bj,`!&aO߼sj4 p dZ&jkBa(c-gD*&meɀSw@@0?KǗKF [uxXTe&T}шI/窮LPLNZމ 2C`lbs#ǰo&i'8E=WJ  D zPm|jv4K\!~č,q¡h+9\avVeF zC"'ÖS,e0 -L80HecF hyr?KPXbEDXrvq83G(,sC`VtoV2/y{i6͡u7VnsMsx-2ˤ^ˀ" iP%¨!DT@ C}e Q`7&x>~B|qOֆ`"량q}\9QH`z۬2+D郻M鈟#nT-RŸ?}D|r 2=1}Ŷqeyӝ;u~lc{$aQ{$5{ggB $F^K`2H@;CNfg[p+~yE|6 3?M[U,"YY@sνWuj`aj  0*en\~2&HpF FR{:9G)K<*ErU 9ZUTP2"zq@XL$`aSz#y,F+Rd=ZdrJ 0/̑sĤ;rPgAnG`b(ÐE_`ag  0O޼υP0zpd8 : (!uGgy۸[bm嘆޿n4Pĝ]r6#\ml六F1t&|9SOm,܁0m3^,Tɀ1UˉɀL2ze:( a濹G$Tv^,}..OE'dYbghP: U].y)݈q21{E6e2?W7:zR-_2#p;6GCNN1z|$W {/~ai77?xwP-th^q&z$ŭ3)>\vL@N@>0L9Q-ֈxQaazc  pjq j;?ԛgقA]XX&(   ># g uA@@`ab$, -/^,Nq`v .3.V!j4H6 { s5CG{KtFd=p rn 4M&^%M/'Oz.v·9C_LˬɒYyĵ@AZfi?z/S38'vUv˖B +J$֥r-"85D/ !\gϞ=x𠋑!*vʨZ0Q$lKs >h!ʏٛخ.DP͵Pt j00^ SHڵk݌'{ŇFӏ%=䑸]樊vh#N[1q d$rK2H)Ktȱ:4tЂrv=h#`&ii[o+h0Ћc -=!s'UTerd!.r~6TC,x9bky+q'ʕ ;!q}+^}vWRи *N堧!<OHbLV2H?5+USN =& c`t 0Ξ=SuoQN99(.~\x&%[,FoJ((SmD\0k/$/8ԜB-Jb] 3;I]\g}ZCp{ qb1Y˜UN "pΝsA.^JWL|\Q⥬+eez\En^PJ駌zƔ`S{l[ReXxdφ Ҽ _rJ*Y~ ]ZtN#tIX` C0@`t3/xuJ!uCۚ 8si&}Jژ_;Y!X#6Ը䏎] ]G%ñ%[s\*J ^Q8)|9SOmαJv9qp=0]YSNd`aL@5S$pGF`1',PdՖ~}d ^\;Cdv|Sis]ad[!vm4A:V\n+nD=u1N!_H^Wd  P78 SLcv'_;W {/~ai77?xwߙbtN篼J^hUeGRtkcac :C? HBlu#2ce1O R+l~t7LH,@70|xOL!@@@ )$L2fSMTS)?T77^ߒܧTY(^FCƉOai[]mwOI^6`aLb^ d0 V".NXR[t']7 mXlCw6"fj(6jYɲX5,! cz  0R'|[9b&e CEͶDӝUq&6شiJT -)&y3͒7aa`i!X. y_ʕ,gl07&gF1 sIhq WFbOc1<첛g*2"Kͳp<" # 0y:`2/m7/(dR+M2+u?TTޤңm-AzYC+fK`U2B2;F*f  ;y߻]/=f[ECZ X,iQ\fpl~KQ p[jMuVP%mZ`[Sdta WFY% cVW#޼hMb aaC z *%i t5IdЕ(Ռ-0m+b2@10:t _~K/?+sbaV$`;'HanYb@6V)mh˞ع+\,vYx'v$C֜PBy~nD, O0B ZGzaYη-)![gJo)Ł'=e)|"wTٔ<.Å K{XP$"cy[SR; ㈕CýpOP 9ƞ o '_;qWJk}޻DOPXTm˾ Jq혱A|SXHǡm*C9`ac "@!\v(ca6Ď  X3Ԙ("XC13K)q1 X3Ԙ(@W/^pCy/Hgio#9M#5&d&ys~%BǃM$SQ\&Օ@S<;s'=ӔkAz(nIFODh 0vvv<y}S>dj3TؽGﳰ&3|!_C^PojFzguXr[8&鳳kc+9kWZBHZӢ I=!  {Ϟ={A#y=J 772MO  +!Vs&5aƣ85ώ_m:JΥ-)/I\ %Kw\& c+A&k׺Oѫ&u/^h$cX#CZ=-b=-<<r-ɎGn_zլ#";}kfBn:ٴsT}rQ~Ts{+0\aB#!xTY=Vȩ `cO/:K} (V)LSVS5y+ <BwRBѭtX'9-rn,뢉fu#fl (4n#Jho~IA>Ryf5k}`a6gϞ}=WWxAtf&S\J.̎' t,_>iLDWV@Dp!0-KH^-)iߊ;cuL70-=Eb,d8K3vȍRJ;H_NBݔeBG\1C#X~X% pZܹsܹ`0h3 woz9ߦw^&^r·0" X,o#RniFd8\}&Ln/f``1Wp!Grنڞj 7zIƐ@`zt3/djZ<f8YxOAt ؘ׃#(SDZ)l6.ͤDKꎑVm-R95VwtN1vv:k#eҦilYtE+O '3g3eTD6Dcg-~=C~@)'#'i҃)<oC۫jvF%)ڟIC&\%U>󱸞@bg0vz_ٹ5x\aw#I |UP~ -ĂNN1|$W {/~ai77?xw@iW^yepF"i &ow6{e,&C1c{JcJӚuu"=?ySl4GZ9cA>h7:>0,Y0_rf3hMRn^7KF@ED- HH,ѡ##Xx8@@@' { 0M5PdfH] G 7Tlu ͭ:m%UV2OhS[VcûK&n?Ilw^O}V˜<g0Fܙ:?E>TltHɁy尩l1%VRjHUn9)ݿj]F) 5^R]oLjhj(dvFr^gp!cGU:]BdYh/+)l;f  `O J}'>saƏ OX֡f˰pt䭎I5JzS3Erf%o+d-t/f 2/~_ .K:wsO9䵯ws |z)tiLУl6 3% \U#@v~۩yF2 FXIQ>R׫,fӼZfWLe] <` },>&c1" + oҼO~}D leߧ8&+/b5UfWC~57,VKp!͇.?uUK:B%ѱV"M#FjI-sM@U_f?L?P!gr63*H`;Z9v1iE,:yPHua!:l7rd.-bk\sX-s,TfG% 0\@Bi'`< o*HJ]JX[HYUewk FQ"J*~:5oo`.:FW&c5QUC3U4kکh#g$P9uЪ'#HOjnjb*@E㬸-("@հ Cy^e銷d&Yfp9~Ζ$Jmn#|Tz.Kw2gT1Te%ܤ ԭe 2X(j0$Ь61+y_~K/?{0<F7n,4jGsY:+HEhCݷۊd%u䢐m #yB=^7 tq BZ !e9S IjgȺPM\ L+7xV}W_ovy<A?Er#"MbUC~ySڄ:yTNaD k],jȎyErKV fBc/cZ `A%aT碻ҦCO 5ܫ!?}`aO5LBpyG:NH |c<>I_*--ߌ_3}k}gZ4P_Z3 %l-M */}=S->^^L@&@Di9&S6.,)[PL@A@OQ̍[yqyKL i K@2i'3o' OL%T&eŤ@O`ai+, ?Ղ ~$ `0:)ȂdNEmu00*Z4TҵmQ&bKt\[4rJo9-d:9aaLZ@hKyiz+XICJ]^|EL-*Jǩ*ի:MF箆EuV.$y%Ke̍뤈1)+=@|M|'׊e3it,B̖n3Q3IaRйc䀲fɛ8  B@N멍c ~lT@yҗKB664rqDf)p?SZ&_W{5ݴD ("x@s\,1e7JvaN׫,fd"g6(nX ., <  04K)*/r5*?c͍ (N`y54N{GE <n5YXaQ&U5kbWT]F}Yj^)VPX1BJYS1AQM+klSG֯=Qs\,&ȷ_t&G KK1Y^2U+jXX3.4Pji<Ź [a7V*LJtU%^z9 Y)LVhoD$1 ya( 3UqT!%߾Rsi(\e~MU,jd5(Yc4AI-p=%5 zYW[Ԙ"/|5qI@|An2 `^tEoq*J?UQޓ|˼v||Ăau TҲ#s,"A?GL,'y!V*Z.+^ެo =<;$ b˜" "_~/cq  ͢ ;c\g̱XX G7GNWF"M#R: W|ڔҎ ڈQi[-Ps*zZИF9gS}Wd 4/vOKɐkF.Xx@@`oFVꫯQ~Ak|HK౉: 5Ȁ̊hez> T: E"3e+zmPHY^rSBU(SĒ Ǣ J8q~9pn1jiO~h_|z89ƘNpU^`if;Δ<% , DT&ZAd G&D`n*c  pj" hsjDS,39˜&  n )[v wa`wf,XfL@' _"~.p `ad   3G-9&   @)@   0s`aܒc³AzN:H(6.GKɯiHGNۀ#v?ɪ nS=Fڔ2sKftm[k! T%M0QtYhP!ݳ  0\pq$Q-2qr-@|oO2x2#RCâ(RWRBu51EE :UlR[9GU/jӘrV,Vh cx1JM>ƹ%꩎ v(H©rz#֮) !hS֡fRi:U֨1?0Tr#Ho(E+ Mǐ5A83*ZfZ$R<h"mZ :covS\;yȒ-,],Ct<jʁ l$(,"#AkZ_C?[iK3yF<#G [39lddze$˜ \,Azzw8=00'?0J:)|#-mf+#uen"P{A]Z!džx"k,k16 OүNr* Zָ\˞"O概XnG :X5Ό.iSLâR JV~ٗިXl !3ڮ#PG*"+Q cuUu8s,vEG2`ҫa]*蔖vQ2;,^=[:L! {jFErj~!P-PDr5ÕZ̓,޲ҷr4 W;to(JZݱjH??%z+瀛t%Qf*fPӶs..F4`ʴH+}{>!˒#2[email protected] jE^I=X= @@c. cTz 2,;mt}w^%U\YۡspФ\*uqǢXNjEPI嵨AxdYYfKэ^=34y[.+ezlС+ܙߒ(Uwry~@< _~/cq9 ]y.ᅾG6}Y7Z_D!C;H\t鮖U硹- n>LXDm +lwvRgJM, *4] \z(:h8o_>Y/"+u5V!!WÚӵbʜIOc0:yf|P{aah x7jW_}oۋ\a 3EQm1P|ߵ7Gy8Nay<2a-$]83]. ,(! {Di{2) `GX,J< L7MD2Đ꜋b\I5+GڦIBgF]NvN3<<@``''}OvsW?k}޻ :N8s\a u~|„:MCLT闿̱eޏ|E{u2 (a8i c\kqA@@-=b'Te5;w)B$ìC  LbN /0^@@A? ZAŋi3 3dcs٭~a2]_TР`]j*$x=5='2WʁUI ?c{rc0oݲ~Waab$<ydD<o[D^K2t -o_mJ*?APvۚs֢Y^pfcȍe~hӐl57 `K`<{`d8A4&t,Ts~fZŸU UclZՎ#:^9=.t(F'mCaay;vK#C8(L/W2n 殠2'HNPv>jݤ(a+0cT]\t߲"m)}Mgr{F{ 2G:WYvͦ:^fzNrZjX^0fv1qpcdpC!Ȩ( h^XޤZ<@PjKVE鬒ZNR@VEyqh4IqXY9k; FD"o)VPI>X kZIcVkϺ^g1YC*E9WǫwʙB`yXYNYTk˜@ٳg>}m,>'%MQUM@F}Wxr[k{g:a%k@HRi7i+S&&aR|k5J]dFjrrTEjE^s~k o+}A@@sιs`<(3|rQ &IJ Um -p 9Tj,8YNZTi\V#rT]TTfWyq?wł  pk^_MFߚnVpDtMxsXNcE=Djn`Z,qk+G+h.6F*LjfD#>`ac $p lN ߬S?*,ohL\ BhG!#cA/;F_cuWQps$FQځ=wE|.2B*ßao #'IDAT)g3]{B +oOvW {ooiW/67?xw0?+ yz/Q52gst$x62c~2F|aLACh#Qc?6$C֬|aac  0$׬[p=ʟ:AyP0&ta, _/ % cBj Ay!l'tYs[c?%;C,m?MID Nd->!&oU+"K(t94k' =+gj3T` 鷺VXMP3%Ժ\x)wwtA@WNu%nl>^Ѻqc+hstTh zO0&pQxF X~ ٵ< AM5Ne=ڮ)Vq޼A&ƛxϦ8Eףf9ks-,RdXx @` CIbJ \\߽;'`I$ѩH>PNn~^摵`𑴄xs I[?NgӦ%y5jOq%|As] EBQMbpyEW$!@&'OI:St֓lN$Vm'hJG Lf؇BuB(V|{? YXDj:iTs{Ghs(êtI_IƤQ' GqүO\ܫ EQ}7Ӽgy7i%\2jF/֋J0 ,oV"X^vW'49D_/VDP54AL'Is]Փs.€,ȑ- U21yN%}<"nF _)G`0Ea ^s#҆z"#dǴ"&GՑ @%f GWXk%dh{cwK,mPKA\^)"6J4(s*3v:KY;‘C)"U1,(,r0m3CggX\7h  'X$R 2!T>i ϙf te[=tdEpF;cc[ )G/$tG[6(F|a !zY`%prN^8Ua7_܌_3}grgͦƲ X/U^g1Veip0i51|$< L^NJ= !0 l?d:D^dHX>Y(   " WeA@@'`ad&, _-ᓅ  xEwͦ" '4%os_%t>r@B5 ILs8m G%[uѯ]<˰0fd1M! læ5OG(tNUl*M7#+ʭi9dzn/.UM: TC8\JjSUP^rV,V8 ڂ{كNpb=ڱ4V=P5kA,gTSFl 7r{eP4K< j{1ɫ@@k\2A[-QM/z<LIpn6FV`"r@:oY_P""t&0\>"$j1FsWXJRn6fQR8u@ BJ`FXTK,U$;`J!5ScƛuppXYQ_; F>B2 j4G\aM+i *ߓFȱb"=PN9:I2^Q1BevF1kL;g>},f7K~nSOJL5D{憨›s[k+8Bl;HG^B!㚨C+ܫKjD1B!VzEj%c!'ƾCcX~X% ܹsܹ`08p9L˕ -p(aHf}jBWȈ9b҇j?Ž#䰉wf̮3{˜٥A|Ly!|7qK0Z(S 59b0ʱbٝ"rGfM*x'J$#gYf?mK>c"cD3" _0fx1i&@t4vv l9PBܺo)L"O`*$e@fzv'RB_ ]4 R|a0ˬv,Ed %ЎVnIF7&y:Оջ"CO!Jou%͸~lC&۬oA!pr1㓯&~WYZ_fG;CrfW^yef\ Xirk[e&#|@P@`^ty&"JssK=|6X2\:E<wD˜>  JIA{ׇommN$ۊA_X~X%  ~# o+}A@@`aa#, 7pJn *`p)f'Sɲd.ws'IڋCy16Q̸)O79M,$D.IdDب-Y cWs'7ّ SiYJtաn.dT~n5^R]x0,^+tʅqer#I8<EUbI!<ptX„(gT`o1c7bCSo*kYxo(}@od81LQ'i(Q~yZLۀ0mE1Y]sk2P:O Zkc_ko#@`$[ ynf)N#h${]2Uh5` a8R׫,KTʔT4>z&YUX: $4[#J1F%:ȑLE+ <všAF6(0D)VPjIb%TzѿIչ(*@VE3fC|knUqˤFpeTUDx5T]U2I)nI:j%%@LٳO>UBHnbmn|5<om%1 Din%hYlEѨ(& #F3DRO|[qXUYUC.ЛMbT#0< 1  0.ue*b9XC0>FݩJ62*"JAniJ1yEZ(JTj2T-+.X@ ;`0| dl}ۿ)nO%J? qbNݛA@7*, &)5Rk"%KD觮j]\ S^'fZ,^~L@`Μ9sܹ`0. l %ݶ5̖%UP+ʫxlI;#M.&F08dœ)+3*+IF7:{$= h"wRⰒ4 \_Gjv-  Ђ eZ-H |c?>i _5*Ugi_nƯo~{3R!;ϟ{[di5 {KLN<sc&_4/+=A9>G3@Gl/0/% [BU'd!F<R)"c#ׯzJ2WjN2u$'stX. @\00v @``a1F# c31z@@f,[s@S/^)y/H'N[rF@R|i۾~4Yڳ/1p "!hfp41A_}91)%\Y;M粢Aw0Pvvv<yE˟RVm u?ܺ4VT̬fKf8x)wfDa?([EUitY8 y7om wr]cݛn,ެ1+yxDٳg<fd<_μ&CakqVGs:U1M5NF0)BiB_؛trZNxbK\ %KO cZW8==*_&׿h)wLk|7&~G[C~<o5i{Z{p-ؑoADqV tvqeڣr2֬/.պD^, <  .FF ͑+>2cuҌrrrV< ۷7ͩ􎼕2[(IK iLer8j;DuMxV:hĪnF.pgW-rw*}^f9!AzpCN\ѼXx>@@gϞ},́_ :<U*%|/˄pfcW"G3,߬߬R3y<+>ކKGR&zpF;0Yx1 2qtff'4izbX0 $̾=X_x7OĬK1O u/ߗ!Ī':ʸ 붑5CW $<˿N %,?Jӷ5 9|BdQa)9tINh0vi11S#ݼhۖa r+/3r˳S͋k ib Lh Mno{=۸[b-a X1I\^ZBaL=9v[grPz'iTܞ<=XY%8s̹s#WF0yD[@yfƇv(){RCF>OȚwݻA:V^hi+<>S"ODž0WNN1|W {wEK5͏>yw\)F] <:Sg&v6ch,lC6ƢĔ Ɣ., pZ`^ J:Im{TPXI`a8mZjňO)u3+~/3mLnm`ay0<L%XS,1/ ng4@*8G@@@{0g ~$ 7j9tdz4Nh0W2٫gVM;r\諽0m +)y/Z?%,mlgS1M)^ŭ'74, aB t._vڷIC_Lڨ[as6dEB'R854?RBZ`}/>F6]y]*e `z=3JH )^ gϞ=x𠋑!{Z/QgdKgoV-m!gr.ÿUeiЕ*]EOBɒk`ay0<R+)N99ZxPH79jc#h_?E"$c ~xbMvjh|;%H^BNHRaŽ'<kwc:BQ}]T@ L9FFX<>wrp=/.jmths矲R\TTWrH+q'%j}A׼rz/ŲPkո0R>qV|P+lĊ+.rʛ7j,zXIMƸW`0PϞ=S{ _]`(i`^6=Y^~a|j-"qN›c+cV,7Ya\ ,+QHI]L(bHp& ,\h 0갋HL|D_RVW͇voVmd)S l=lד+W&ItыI^eM -'@4 -0+_<OS3A諔)`~gmHy/\lOet+Nb ycwKL*ۓ 6[Z]e<T5n0ƽ@`29sܹs`:ŜHPd£ekOʗ~}d s  Q\Ca1Z7:ʈ_ad!cD҅kAu*V `+vJNX$iVxl A+ek(hx 0#NN1fz|Ӭ/W/Wf;Ό`t3ϟPmxfhb7<sq4uay5C>~h-y1#$  !]! cz   !1^|[obu:`t, <   =SHg@@@{0g   0 @:u9<_ )nvk*]Kv*66".~&ʚqDE%i&=p rzj ',ZhɒNk HoUBZK|u*]Ԅ|5rLi)Y\ϮItfz i߼Mg_.o^!iVC%f3EפBZ.:֢%EH>hhj.-QYM\/RLr-s^ u-, Xd穜,,\VL f/59grr,樊Cjc#h_e/d"[2g~È ́nbMvjh|;ıiZ$eO;H4aŽ'<WN!b?MP{RJ>u3$, -hZNrڋb"<"ke?$hC@DL%W qQ_ʅtBwR$ST{.ZƭtUG%\7݇r_a#V|_Z캨½AŘ#\%s@K޻ }G (4'P2"@?DI ozƇ IXfJ:/jZ{ ghUrE 9))mx?e7yBqv1'/{ qg~5G`a AJ@T03L|MD⥬+j=pT zCo#Ktp9퍍2.ú#[#mƽ"[\GW7(K^UI%ˏ-7A9d%irUX&@4"3H@d_ƻ[745~pf~glG:(rD["oAet+[MHw8cwKL!*ۓ6| ^RD(6坈O@1GÑ s㉥# c3i!X̉ EX*YfJ$_}C['[Ov Hd:_ad!Nv~jBqknHl  b䀫HEҟ&a7v1!_H΍ W׬Uf HC㓯4pU^?j3~|w{ 2T MFsܢRԐE:҆>!O j@Vjݼmz&/ފ4ᗕ  _xjEpv7Ji4F0qU1'7a{0>t%0y,r 7&W7h ab$, -_e 0hkw}o{]Nm^}tdj}ԦvUH2Sni%囅[vr4IM~6?Zfmj9؏4]@  _uqIߨW}/HzgF.X<xyka?\ ~RQ-%  XL̅ϑyѺ4~}ώ-܋CmQNg,XfLD&Hgk?ͰG7Y՟F[˱?!Mpozn09'"#', XcHtx> mhEqMw{.GLpG/W<&P~ko0 sl5; Xb:ZiNrŐ&Ŋ;inl$󃅗W=Z4F^W{Qw'#|y+P1_+.i =aȞB~G*-s1Ej\we#u :)܅o&RI~b"?!8Fܤ4r~x謹) @X{Г$Z).aE'd w\J9 ]h>Afw߷2Ffϛi^JԊYKZIKڿĭ?V1;NdC)V LB><&ߚI?K8>Nѧ2%F%Hkٹts.oI/p΍}?8C7ͬ1++y p}DQMcCv|voE|w fҦ!c!~zwE-0ݷ{21|--B12Klu#kE'w 0v$ (og% (Gi2/rJP!"[;kxϊ0A:lō4irk1+CDrS4=}^.\ 0 % V-E'כk}޻|]@]{_wh^ ^g?V ꒌe iP0i51 J"4xqhޙ2 >aYd , .T.|2S4?ɴ,S C, _. '< _ 7(taObƬ.SM>^^L@@DƘcXj0zy19XcaA@@` ˜@@@`L`a <& c11&@@,^^L@@DƘcX->-_HIFODh   7X}#C`aD   }72tIFODh   7X}#C`aD   }72tIFODh   7X}#C`aD C84܇A`˜t@@@`"˜e   0e`aLقb:   0`aL2@ 20lA1@``a} L!XSg@``a} L!}\4S4IENDB`PK!0C)word/theme/theme1.xmlYKoGWwŎ -Pqwf UpT*z(Ro=Tm@~T- zcTߏ/^3tD<iyUM–w;!p`&Dz?"R Dn)nU*҇e,$7" "ߘUz%4Pc`{c8>A}۞22J >5( 6CNd tY9?C K-j>^eb bj mg>9]NNkl^-Sn ~},t)cZ{ʳʆ;faKvi (6NP6l.t-e|zPh2Z@x) Cή8ߘ& U)eWFe;\`Md}up<kxN˅%- I_TS 1x㋧ɽ''~9+8 TϿWn,~ Te೯ѳo>2Oc"urx 9x=~ib' %Nq*'ѱpmb{^߱>XQj[=Y MWI.eG.ٝv)4-mhD,5$! =>"AvR˯{\B)jctIl]1eRmfjsbKl$Tf.Yn NqkXE.%'·.D:$n@tKݫz3{lHȅ9/#w8uLH E1ʩ+D!8Y[X~umߤ,AXJp'la^1M^ָΝI8 ٷݝl;r|^o.w]<N 9o漬Ͼ%Ϻ9OچM= #פ zh&8 sq.، f$2gJr W 7R hx-/3 ͅv*hM3XUڅ eՌj #& z=  3ӰydH۽hHm65SH[%Heq%;M fQu;W,gj֛qp܂a?[fa|b7؝R-j(2[9Kfכ 퇳1эVbm0rhpH|de6Xqh:UJxU\jv`fW~^ՁY'Z͸J9SgdJ9g̅Z>F:G[*Ѕ҈=# BPZ%/ZWr4[SPpbQ4DBS d_vY-ye>S+9 Guk=MI=ϝ1u',m^x0ѯ*Kөڬc-7W~զpMA 7>oD eK1 @l1Yec,9g ]rqo|dGWWKRȘ?Y|pdh̔4p)L>DCPK!ٴ?Y 0word/settings.xml[nG}`AȪ}!,jq'ْ&D|by9x̓unݺ.ovuz_EYns=}tݾ,Uign7aίvv^vC]?=q{fvn|%3z8l'n1n?Nwwݢ=9g/fXjhWC=tݙR#Lmzu~S?,? ۡ_)h:3m^V+Z)sF@|E`ۡvrz1{vEVI۹ fo,| 4cul4:۰Yatsۮ_6 Cp{<ۛ}U?6-+N+.Yf,H~u~@<' ㌇pl|${ƁJ7Unn~ H x~_zvɏk5|s_rL拉Gy9i֤/û~I47qA\t"Clߏvt^tt>Z}GF8#͸dmm#YiU} C?,CbW`qrί2U\qˋ`Z[N ZQ!tˆIt"V:$Bh1R;8&dLx1bĈԢ(Ild&rDpa\`Ȧjƈ)ت8Y%"LP\i5Ǖ1<$(ndbph6"%ܳl S '<', DRlX:պDpu*JTH kXtPBI7FN7%1Dh%cJh1~ax!"Ԃ,1R`9ԜR9:h!"=X k!a$9AL9F}NfpE ^0bOrMf:ThU@I jAJ[TYLMtFbJ,g<`y,F>IvͱSK '1Ux]IByw!+ rZQyA)k(#C¼2d:N u8C%kP? c9]+zY,X {eDVGeި*X?T7w)ah#8{GBтMrVjÍ s`pPz֡jɵ0B !sd 0(9t# .d1E -'젘§7ꪬjp=EYFけ*ihUF`jJyR`mbpo,r0V\EoQOy Za͙.93\mdqd^8溌{d)]S7pbf /bqLHUVBO! $DtPpkXKfNɪpg* DAD-fIj[N\%huo ڨMTh3/xYGlDs F$[)axG>r q!+s8~"ځF|rUvI,k5ÙvN=e סc 1ڨTDBx) ^:y͌hmBY ʍ[r|,z\zpL u곐D/cHejbU[L-0nz;-La 8Xi #obuH"$\M j?\"1`]AԀax*0` B$aި&0$co&Ic*`?"8ѐH5 GH->s28D >9T;!D™6R>wx?t,7q K'Dsc܈ePǼUji'(`%  QIZ155u杈5\+';8$CdxOC$'3v8c@.#R:pħR1$22)鈳YW|ҘF9K7S %9b.#-$S3A>&Dἐ50dm2EPftzw$D(8węj< [()[,B 7Odo 4Dh-A@iO hR*bez fjb%?%vP\P~8)hrFxX ^{!o$(|WpY [HPgtMXIp|RRhL .bY7x吃:^r\$|VVW*dgiUD!UJUWIچR KZ3 .3!QjXj_EUgjm'13Fu*_x%ͫ=zp__0Rh5q`DIr#{z=OuqFjַC\o_ob9]?#7gjUfq"Xϗnۻ]3ܿ=1e{'Zv?nlϯAzm?v<k ϟA^4?uûכaa5׳.OG/Vx}lǛz|_fpq{/N8`~4qeL>{O˘:1}/c<fƱm;͇٧q_v}۫/ol&V/EGz}om34~8c8`\͗-9=5AC0:3PK!&kyUjKword/webSettings.xml͏:;C;[㏊. =M݈$ixlj~U68ub*mr]3_,Ʃe.nX8~q"GU[iWX]ŶR|qpluJm_NnvJf(i2UmC1uUݏ?$> ~HU<msזuwoںҘvY~SrqPTmzs٥4 d`[ߌb\M޾<\)[, 6.S}y?_R{E'?Wb;̩L8E>͉)]&ezJ̓==Styk   9mpp@ԗ pH`v)8`a` =HZo)A GF8Xpz @Y$aҞ;XpXP>VtIgłP֬p`0;+/,8DlYp Z" Pea!(A.d iV<xK^1D<xHiYhM(/k%L<,?a i<<gjaUy_F&DR^<~x0Jaɯxxxe-M;#Ax+.@C+Vt2d2`*X0Aă[ h?xx&7-yXJT* Cڏq8~Zln?t{{8+&?}PK!hqword/styles.xml]s6~8z{HmYegvlǺdn Y)BGRqܿ%(.ә"v H|u|Y|4p4dQ>>_ iD3G|:/ _Ѫ(6pE$mhO.Y&=Iݼ zCx'q|ptxx20Y\!}횦?hYM^=A{bYXH:Qxkx q-oI(.>>1X=,#k$`#KM\n3SYZkq|[ 㽽HxPyLZOg¼0_Q<:-Hr>::*\Ԏ%$}(;'ơ=݅<75nw%ސ0eAeqbh C>?~ ݒmt#@[sw>'G-~,fٙ>xG8hj\ǜF?ͥ!ۦl, ɣ!gS"8 q65.[5m+JDM}đȍm6]^jhR M_jH:K44{N_! %ӈ~Vp,ވƱ8Khq,Ʊ:bh"p ڬ0ڻqn7#?n`UVYZ %cE p4r,Yͼܤ@<-$~ N> 2XیC;NO4em@yh,q.iFӐ4l z67M#+ʠyN{05 36kx7q>\W$& Iᵁ^Hᕁ^RF)Ia͓ޔ}қF7Iom"!:&.~H O7z4%yfYvX\91UHzi"Wt;\54_Uyr ϓUx]=OEO=s]N+z9I*mna;Y a=X :}D]/wl5ܭQk4^&,|>oh˲Hs$F)[3]HRכcY+ = ۄĩޮ_I2o{ePKVl SW^"8}t$UaQH,8`$fT-:)';ިÃo㏇lHBX r{/`ƴa]F -Lu?iB nx Ã_7[~58_7{<P|n~%,[n ,iBli%xףH<Sr?Yy#CbBA@y%` l2lZ)0|ٙS̗I0_v&|ٙeg7].yo1 }ٜoI ްdϞ @<L*ی-,U=@9c|+]x/3$I4p1qx|WL1 %,dz-}ٍ^Ӟ7êVl srW,kblI>K{uQ2ɤt.Ime5YOIiOI5.xCVCuOUYoeEpk]TIˊj\xZ3v~cxNv~erX옠)۫VO4$WiԼ}S)iЊ3eznwCDVqTHMvAVpDE+(VP%ZAh5 CNhGhG)!P ĝBB&`8G8G. Q\BBBB1;9*DA;*@;*@;8*9*wqT@Q! Q!Q!Qի q ]8*DA;*@;*@;*@;*@;*@9*wrTvTvTvTpByByG(. QЎ !Ў !Ў !Ў !Ў !P ĝBBt٧~Di[f?zZWt;* 5Uʎ]K'/)jcuW.@= }G)s*.7%A7tSdӮkJapt_RpŒ!<wEkC+FP] džq sSN ,!We8ї4;B_}i#CCQ KTC';ʙjF5 X!jlGpS PnTá K5DR T0TC(g!0R TC,jN5rBQ d4K5DR 0TC(g!TrF5aCgCСZ2%Z\%4;B_}i#CCQڨvwT;j\dW-uR:UKvqRոjjlGpW-uR:UKvqRոjj\F N5ZW-٩UKmT㪥6qRոjJ5ZW-uRT㪥6qRոjj\dW-uR:TKO ܐ_\<oLA EFIBX$[RòjQ iO+>M&n{%‚4Qh4O+\HU^aw/OWɅv!}#}yLS_VT|Go͆|J4s]o8_ۨ&ۨL6*[_; ѕϤHQi#"qwXగsgl|ݷ<f_bIGVKTK۶ϸ;}5/،iJz4<6Д&VS+ OjJ'7F2^THpzr5т_H|F! 9[$ԟU;Mc|bel}ۅ߅/;,΄PVK?D ]* IΩz}& I򞨫~iBBPB}*ɪ pPm'j\ϚԿErPMcÞZ:8,I`7ֱ5m.#oŰT?H}3:~rD~NjNtE[ihKLJZhxt!z.g[sJ%A/|Ye"ZHgtUE 6|Z9`â[va͸kM`<jF½_' GjsGlbE7NUxS!:] _u>ENSNb~P]7XV"/Mѵ+tQ~O[ug~x@}H7 È[ںjqKj,ehت۝L7'lRZv0`rhvN4}v=;OT{Za^jp4n 1TpsCҴv־}WӂY xN#jyM EMGzzO.}Z3fet5({U@FzI ,t횺/]N]: "v/njTy*gbkE-O U>)ZeG^֑ЋܧM%2NK \a\#ѵM-)Wx5ij]2j@u!.MTnެj.=Ȥݻb38}Z}ڮ7g*襝NrliLW='̥5#oj\6m\Y׊4ą`v9;օ"XO<$*`m`kZ:}]ZoMV'd+cs t>egFF;`X >Ot}WW+ìĩ(E{EEp>vJ@cU)9L(Q.~v~$3$||6vSř;Huge?+sacˆ/ led׽3'W/}< W;|o<LӃ8-Gzy;I6w:bwy 9P~.738 kNR01<Q'zG* !ZSQĴ=Z2L3/{Yy8(yzrzة kd.9934`ҩ$oS?֚按{nRXBۚPd(I:5Ԛ4+PK!-ua ?word/numbering.xml]n?Ȣ[#`22Zi[(og>&Mi~!RK"U"$J6*ֽuw:]=l8In:#\`r7Ln:}p:Wy?&I|yg?O߽\'O8NHf/Mq>^wc<>t2?&~8/%_t2g<gq4N/'?M~C?Gk7Ln:Oir]ta5Ek5c"s]$ q2ϯMQ6I2{Na[㲓g) H/ N5=RRcF]Z5# f͹T6mw0}h79K'Oӯ 9ebi7諘ufcC2IlDٔ]e^ZuSvi0i|绛OIfû(;B}.G:7|CN9FԹt<uKxSߌ_ ?Qv"(CvLTxu. bY___W~\`yt?0Yع8|ӱY>~߸-N}mn5G?|P! L`%z&݉ɸT[ī,JMb4:5L1ef6Dbc0C"Z̐.dc2 LG :y u+tqn<C${P$hA6:Klv]wh]Y< )\A$+/WoFЖGMcd\G4I泅faFzNFyS/Ɓa2_,~晢(`joLeKe;[GͼV#DAoi뷟Zlkǚ9nTA>rsWbJgQS;WaZqejw+n;Š+ijXqW\Ɋ+㭸6$2Δ$+/_:+7fe̐Y 7EkL :X~:^sx/x|Z&B8ΕK|$ic_8_@ ĠI  -툁A z%˔X6d5١Uɐ&C옌i2ɐ&;C iSd v>g%e+ϭdo!_A|e+W ުQɥ){ac+;W^_xIxFFb o3G^ֽ|6og#!}#5KC/A;Gx#8<kߧC~p;eC<OxP{e9Mb<n 515^#851[qkR^3]qkRrPC*߭X&l"3~$asNj<}1XsRV)+6 )*nq*LDd˧sV!,rЕ/ `S  @moʤ w#7)u|[ <WotgJůo=E@x I@7DrITP0EH@ 8с@t :k܁&xP ^eDс-\P|}t}w{aI`oʅyTDy%^C>_@x I@7DrG SC1~E:@x <˕ŋ %wk!ihpx`*?p>tʏ{ʏ;]ʏxʏŶ b+DۂO=*R\(@jt ]}+t^&^!:(㦛5@L@%Z"< mQ ᑜBr )$BrߐjI퐜BrOr+JkEIM[Uҕ: j9Z+HW߲tUd*uZ=R:~ +HW ]5+HWf+ҕي{GU'n(댥+k-t -{ ]AjRZvb\[ϼK~.خڙ~_%UWR)0 14@/ZA Dut H Ŕ08s1n \r]u!u+=BkkB$rkpp_o}&!jIL&_.mPʞ穡KW>"WV ]At UAte ]w$]_:M\ّwf[!y5UH^ yA*[t>/Ͷy'jY<ҋd~ ̠i-:#fL`thWf &}b@_;l佛#<l/?^v0TpI\^/ c?c~yGZq{{\؎"XP'4&2||l}@lAlAlAlAl5[q f+lŝMrB("nLYjX؎vJlGuݮnjکZr zG;UrکO~TvRL=WLMЕ&ZnT/TP0\7T1bWCMȨJ]jbj ]QMP3]hj&(MC}F73fx?QPu^-^{P}E4叫B(/WPMh]②jn7x+)U6T5:8,+j6N3PK!6Ur9mdocProps/core.xml (_K0C{v'ŷmI\oom{r9qMV|PԈe`ʬj( F;hT1a=yG!K$p5ZAAP$Izc* ;.~ pI=H)FC L W/ ʙSspzG6u]MkO}5WߕTR0G iq-qvT vIK-տKCXV!LY bлS.J&>Pxg PK!G9P< word/fontTable.xmlԕM0z(!v&@@:H̢Lյ XGd'd8CGo۴s$ RHΒjÔ\H͘܏OuLJp%]Q߾qyi"4MgĴTB%LJ ­{Yr)Mgk}cw*i)E%͂%f+=K1gK=A"$XQqڂͬ3*q+wfV@Ds4r8 /JL/ P SK.jfEmمтhCF/16QDh/f6rʰ9Ldf@gq:5ׇ #xo +T@<1AHsCyF]>\D7>ٿwDFuH5"-.u'2RfT[&Ght@bih5G̞_c ::9)ON!YFΦ)qQ vP~093q (܍ |(zMAQZf$.* Ԑx&.#1abIxM?}z+F 7Qm ؚ= [Dse[T,O=R+w ؅J;}J%NJ4z'-QgJsi|X߬4͸>8SN6 PK!ѝdocProps/app.xml (SM0#ܷNrB]=[ݳq&c[l3Nhp9yy'Q;)YU`k=l(m+)[ !X׌Eu^[:\%RuVpKټ1xE-7~,G Wu*Oٓ H5ifÞCi݃^r6"B|Q81e ^K{DUpuX< Y"{P/A9yCY_ 1ELN!+i`K]48M{i;OЅ"4yY|R6I--c A4 iO륨׉C0x |n:l<V3;K?TRلo]ڐ_=&?k<Ti>eʗ ;{bNS~Ow&UKiWKf}]8Z9PK-!~ [Content_Types].xmlPK-!N _rels/.relsPK-!4zeHword/_rels/document.xml.relsPK-!ɉ-F#>t word/document.xmlPK-!w˟;Gword/header3.xmlPK-!"'P;Iword/footer2.xmlPK-!O;Kword/footer1.xmlPK-!;Mword/header2.xmlPK-!n;kOword/header1.xmlPK-!KuHQword/endnotes.xmlPK-!wSword/footnotes.xmlPK-!;Uword/footer3.xmlPK- !uΣ''Wword/media/image1.pngPK-!0C)word/theme/theme1.xmlPK-!ٴ?Y 0word/settings.xmlPK-!&kyUjKFword/webSettings.xmlPK-!hq͔word/styles.xmlPK-!-ua ?word/numbering.xmlPK-!6Ur9mdocProps/core.xmlPK-!G9P< word/fontTable.xmlPK-!ѝ׶docProps/app.xmlPK7
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseLocalFunction), Shared] internal class CSharpUseLocalFunctionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { private static readonly TypeSyntax s_objectType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseLocalFunctionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseLocalFunctionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodesFromDiagnostics = new List<( LocalDeclarationStatementSyntax declaration, AnonymousFunctionExpressionSyntax function, List<ExpressionSyntax> references)>(diagnostics.Length); var nodesToTrack = new HashSet<SyntaxNode>(); foreach (var diagnostic in diagnostics) { var localDeclaration = (LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken); var anonymousFunction = (AnonymousFunctionExpressionSyntax)diagnostic.AdditionalLocations[1].FindNode(cancellationToken); var references = new List<ExpressionSyntax>(diagnostic.AdditionalLocations.Count - 2); for (var i = 2; i < diagnostic.AdditionalLocations.Count; i++) { references.Add((ExpressionSyntax)diagnostic.AdditionalLocations[i].FindNode(getInnermostNodeForTie: true, cancellationToken)); } nodesFromDiagnostics.Add((localDeclaration, anonymousFunction, references)); nodesToTrack.Add(localDeclaration); nodesToTrack.Add(anonymousFunction); nodesToTrack.AddRange(references); } var root = editor.OriginalRoot; var currentRoot = root.TrackNodes(nodesToTrack); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var languageVersion = ((CSharpParseOptions)semanticModel.SyntaxTree.Options).LanguageVersion; var makeStaticIfPossible = languageVersion >= LanguageVersion.CSharp8 && options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value; // Process declarations in reverse order so that we see the effects of nested // declarations befor processing the outer decls. foreach (var (localDeclaration, anonymousFunction, references) in nodesFromDiagnostics.OrderByDescending(nodes => nodes.function.SpanStart)) { var delegateType = (INamedTypeSymbol)semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType; var parameterList = GenerateParameterList(anonymousFunction, delegateType.DelegateInvokeMethod); var makeStatic = MakeStatic(semanticModel, makeStaticIfPossible, localDeclaration, cancellationToken); var currentLocalDeclaration = currentRoot.GetCurrentNode(localDeclaration); var currentAnonymousFunction = currentRoot.GetCurrentNode(anonymousFunction); currentRoot = ReplaceAnonymousWithLocalFunction( document.Project.Solution.Workspace, currentRoot, currentLocalDeclaration, currentAnonymousFunction, delegateType.DelegateInvokeMethod, parameterList, makeStatic); // these invocations might actually be inside the local function! so we have to do this separately currentRoot = ReplaceReferences( document, currentRoot, delegateType, parameterList, references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray()); } editor.ReplaceNode(root, currentRoot); } private static bool MakeStatic( SemanticModel semanticModel, bool makeStaticIfPossible, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken) { // Determines if we can make the local function 'static'. We can make it static // if the original lambda did not capture any variables (other than the local // variable itself). it's ok for the lambda to capture itself as a static-local // function can reference itself without any problems. if (makeStaticIfPossible) { var localSymbol = semanticModel.GetDeclaredSymbol( localDeclaration.Declaration.Variables[0], cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow(localDeclaration); if (dataFlow.Succeeded) { var capturedVariables = dataFlow.Captured.Remove(localSymbol); if (capturedVariables.IsEmpty) { return true; } } } return false; } private static SyntaxNode ReplaceAnonymousWithLocalFunction( Workspace workspace, SyntaxNode currentRoot, LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic) { var newLocalFunctionStatement = CreateLocalFunctionStatement(localDeclaration, anonymousFunction, delegateMethod, parameterList, makeStatic) .WithTriviaFrom(localDeclaration) .WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(currentRoot, workspace); editor.ReplaceNode(localDeclaration, newLocalFunctionStatement); var anonymousFunctionStatement = anonymousFunction.GetAncestor<StatementSyntax>(); if (anonymousFunctionStatement != localDeclaration) { // This is the split decl+init form. Remove the second statement as we're // merging into the first one. editor.RemoveNode(anonymousFunctionStatement); } return editor.GetChangedRoot(); } private static SyntaxNode ReplaceReferences( Document document, SyntaxNode currentRoot, INamedTypeSymbol delegateType, ParameterListSyntax parameterList, ImmutableArray<ExpressionSyntax> references) { return currentRoot.ReplaceNodes(references, (_ /* nested invocations! */, reference) => { if (reference is InvocationExpressionSyntax invocation) { var directInvocation = invocation.Expression is MemberAccessExpressionSyntax memberAccess // it's a .Invoke call ? invocation.WithExpression(memberAccess.Expression).WithTriviaFrom(invocation) // remove it : invocation; return WithNewParameterNames(directInvocation, delegateType.DelegateInvokeMethod, parameterList); } // It's not an invocation. Wrap the identifier in a cast (which will be remove by the simplifier if unnecessary) // to ensure we preserve semantics in cases like overload resolution or generic type inference. return SyntaxGenerator.GetGenerator(document).CastExpression(delegateType, reference); }); } private static LocalFunctionStatementSyntax CreateLocalFunctionStatement( LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic) { var modifiers = new SyntaxTokenList(); if (makeStatic) { modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) { modifiers = modifiers.Add(anonymousFunction.AsyncKeyword); } var returnType = delegateMethod.GenerateReturnTypeSyntax(); var identifier = localDeclaration.Declaration.Variables[0].Identifier; var typeParameterList = (TypeParameterListSyntax)null; var constraintClauses = default(SyntaxList<TypeParameterConstraintClauseSyntax>); var body = anonymousFunction.Body.IsKind(SyntaxKind.Block, out BlockSyntax block) ? block : null; var expressionBody = anonymousFunction.Body is ExpressionSyntax expression ? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression) : null; var semicolonToken = anonymousFunction.Body is ExpressionSyntax ? localDeclaration.SemicolonToken : default; return SyntaxFactory.LocalFunctionStatement( modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); } private static ParameterListSyntax GenerateParameterList( AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod) { var parameterList = TryGetOrCreateParameterList(anonymousFunction); var i = 0; return parameterList != null ? parameterList.ReplaceNodes(parameterList.Parameters, (parameterNode, _) => PromoteParameter(parameterNode, delegateMethod.Parameters.ElementAtOrDefault(i++))) : SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(delegateMethod.Parameters.Select(parameter => PromoteParameter(SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()), parameter)))); static ParameterSyntax PromoteParameter(ParameterSyntax parameterNode, IParameterSymbol delegateParameter) { // delegateParameter may be null, consider this case: Action x = (a, b) => { }; // we will still fall back to object if (parameterNode.Type == null) { parameterNode = parameterNode.WithType(delegateParameter?.Type.GenerateTypeSyntax() ?? s_objectType); } if (delegateParameter?.HasExplicitDefaultValue == true) { parameterNode = parameterNode.WithDefault(GetDefaultValue(delegateParameter)); } return parameterNode; } } private static ParameterListSyntax TryGetOrCreateParameterList(AnonymousFunctionExpressionSyntax anonymousFunction) { switch (anonymousFunction) { case SimpleLambdaExpressionSyntax simpleLambda: return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(simpleLambda.Parameter)); case ParenthesizedLambdaExpressionSyntax parenthesizedLambda: return parenthesizedLambda.ParameterList; case AnonymousMethodExpressionSyntax anonymousMethod: return anonymousMethod.ParameterList; // may be null! default: throw ExceptionUtilities.UnexpectedValue(anonymousFunction); } } private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpressionSyntax invocation, IMethodSymbol method, ParameterListSyntax newParameterList) { return invocation.ReplaceNodes(invocation.ArgumentList.Arguments, (argumentNode, _) => { if (argumentNode.NameColon == null) { return argumentNode; } var parameterIndex = TryDetermineParameterIndex(argumentNode.NameColon, method); if (parameterIndex == -1) { return argumentNode; } var newParameter = newParameterList.Parameters.ElementAtOrDefault(parameterIndex); if (newParameter == null || newParameter.Identifier.IsMissing) { return argumentNode; } return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier))); }); } private static int TryDetermineParameterIndex(NameColonSyntax argumentNameColon, IMethodSymbol method) { var name = argumentNameColon.Name.Identifier.ValueText; return method.Parameters.IndexOf(p => p.Name == name); } private static EqualsValueClauseSyntax GetDefaultValue(IParameterSymbol parameter) => SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_local_function, createChangedDocument, CSharpAnalyzersResources.Use_local_function) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseLocalFunction), Shared] internal class CSharpUseLocalFunctionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { private static readonly TypeSyntax s_objectType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseLocalFunctionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseLocalFunctionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodesFromDiagnostics = new List<( LocalDeclarationStatementSyntax declaration, AnonymousFunctionExpressionSyntax function, List<ExpressionSyntax> references)>(diagnostics.Length); var nodesToTrack = new HashSet<SyntaxNode>(); foreach (var diagnostic in diagnostics) { var localDeclaration = (LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken); var anonymousFunction = (AnonymousFunctionExpressionSyntax)diagnostic.AdditionalLocations[1].FindNode(cancellationToken); var references = new List<ExpressionSyntax>(diagnostic.AdditionalLocations.Count - 2); for (var i = 2; i < diagnostic.AdditionalLocations.Count; i++) { references.Add((ExpressionSyntax)diagnostic.AdditionalLocations[i].FindNode(getInnermostNodeForTie: true, cancellationToken)); } nodesFromDiagnostics.Add((localDeclaration, anonymousFunction, references)); nodesToTrack.Add(localDeclaration); nodesToTrack.Add(anonymousFunction); nodesToTrack.AddRange(references); } var root = editor.OriginalRoot; var currentRoot = root.TrackNodes(nodesToTrack); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var languageVersion = ((CSharpParseOptions)semanticModel.SyntaxTree.Options).LanguageVersion; var makeStaticIfPossible = languageVersion >= LanguageVersion.CSharp8 && options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value; // Process declarations in reverse order so that we see the effects of nested // declarations befor processing the outer decls. foreach (var (localDeclaration, anonymousFunction, references) in nodesFromDiagnostics.OrderByDescending(nodes => nodes.function.SpanStart)) { var delegateType = (INamedTypeSymbol)semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType; var parameterList = GenerateParameterList(anonymousFunction, delegateType.DelegateInvokeMethod); var makeStatic = MakeStatic(semanticModel, makeStaticIfPossible, localDeclaration, cancellationToken); var currentLocalDeclaration = currentRoot.GetCurrentNode(localDeclaration); var currentAnonymousFunction = currentRoot.GetCurrentNode(anonymousFunction); currentRoot = ReplaceAnonymousWithLocalFunction( document.Project.Solution.Workspace, currentRoot, currentLocalDeclaration, currentAnonymousFunction, delegateType.DelegateInvokeMethod, parameterList, makeStatic); // these invocations might actually be inside the local function! so we have to do this separately currentRoot = ReplaceReferences( document, currentRoot, delegateType, parameterList, references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray()); } editor.ReplaceNode(root, currentRoot); } private static bool MakeStatic( SemanticModel semanticModel, bool makeStaticIfPossible, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken) { // Determines if we can make the local function 'static'. We can make it static // if the original lambda did not capture any variables (other than the local // variable itself). it's ok for the lambda to capture itself as a static-local // function can reference itself without any problems. if (makeStaticIfPossible) { var localSymbol = semanticModel.GetDeclaredSymbol( localDeclaration.Declaration.Variables[0], cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow(localDeclaration); if (dataFlow.Succeeded) { var capturedVariables = dataFlow.Captured.Remove(localSymbol); if (capturedVariables.IsEmpty) { return true; } } } return false; } private static SyntaxNode ReplaceAnonymousWithLocalFunction( Workspace workspace, SyntaxNode currentRoot, LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic) { var newLocalFunctionStatement = CreateLocalFunctionStatement(localDeclaration, anonymousFunction, delegateMethod, parameterList, makeStatic) .WithTriviaFrom(localDeclaration) .WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(currentRoot, workspace); editor.ReplaceNode(localDeclaration, newLocalFunctionStatement); var anonymousFunctionStatement = anonymousFunction.GetAncestor<StatementSyntax>(); if (anonymousFunctionStatement != localDeclaration) { // This is the split decl+init form. Remove the second statement as we're // merging into the first one. editor.RemoveNode(anonymousFunctionStatement); } return editor.GetChangedRoot(); } private static SyntaxNode ReplaceReferences( Document document, SyntaxNode currentRoot, INamedTypeSymbol delegateType, ParameterListSyntax parameterList, ImmutableArray<ExpressionSyntax> references) { return currentRoot.ReplaceNodes(references, (_ /* nested invocations! */, reference) => { if (reference is InvocationExpressionSyntax invocation) { var directInvocation = invocation.Expression is MemberAccessExpressionSyntax memberAccess // it's a .Invoke call ? invocation.WithExpression(memberAccess.Expression).WithTriviaFrom(invocation) // remove it : invocation; return WithNewParameterNames(directInvocation, delegateType.DelegateInvokeMethod, parameterList); } // It's not an invocation. Wrap the identifier in a cast (which will be remove by the simplifier if unnecessary) // to ensure we preserve semantics in cases like overload resolution or generic type inference. return SyntaxGenerator.GetGenerator(document).CastExpression(delegateType, reference); }); } private static LocalFunctionStatementSyntax CreateLocalFunctionStatement( LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic) { var modifiers = new SyntaxTokenList(); if (makeStatic) { modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) { modifiers = modifiers.Add(anonymousFunction.AsyncKeyword); } var returnType = delegateMethod.GenerateReturnTypeSyntax(); var identifier = localDeclaration.Declaration.Variables[0].Identifier; var typeParameterList = (TypeParameterListSyntax)null; var constraintClauses = default(SyntaxList<TypeParameterConstraintClauseSyntax>); var body = anonymousFunction.Body.IsKind(SyntaxKind.Block, out BlockSyntax block) ? block : null; var expressionBody = anonymousFunction.Body is ExpressionSyntax expression ? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression) : null; var semicolonToken = anonymousFunction.Body is ExpressionSyntax ? localDeclaration.SemicolonToken : default; return SyntaxFactory.LocalFunctionStatement( modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); } private static ParameterListSyntax GenerateParameterList( AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod) { var parameterList = TryGetOrCreateParameterList(anonymousFunction); var i = 0; return parameterList != null ? parameterList.ReplaceNodes(parameterList.Parameters, (parameterNode, _) => PromoteParameter(parameterNode, delegateMethod.Parameters.ElementAtOrDefault(i++))) : SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(delegateMethod.Parameters.Select(parameter => PromoteParameter(SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()), parameter)))); static ParameterSyntax PromoteParameter(ParameterSyntax parameterNode, IParameterSymbol delegateParameter) { // delegateParameter may be null, consider this case: Action x = (a, b) => { }; // we will still fall back to object if (parameterNode.Type == null) { parameterNode = parameterNode.WithType(delegateParameter?.Type.GenerateTypeSyntax() ?? s_objectType); } if (delegateParameter?.HasExplicitDefaultValue == true) { parameterNode = parameterNode.WithDefault(GetDefaultValue(delegateParameter)); } return parameterNode; } } private static ParameterListSyntax TryGetOrCreateParameterList(AnonymousFunctionExpressionSyntax anonymousFunction) { switch (anonymousFunction) { case SimpleLambdaExpressionSyntax simpleLambda: return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(simpleLambda.Parameter)); case ParenthesizedLambdaExpressionSyntax parenthesizedLambda: return parenthesizedLambda.ParameterList; case AnonymousMethodExpressionSyntax anonymousMethod: return anonymousMethod.ParameterList; // may be null! default: throw ExceptionUtilities.UnexpectedValue(anonymousFunction); } } private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpressionSyntax invocation, IMethodSymbol method, ParameterListSyntax newParameterList) { return invocation.ReplaceNodes(invocation.ArgumentList.Arguments, (argumentNode, _) => { if (argumentNode.NameColon == null) { return argumentNode; } var parameterIndex = TryDetermineParameterIndex(argumentNode.NameColon, method); if (parameterIndex == -1) { return argumentNode; } var newParameter = newParameterList.Parameters.ElementAtOrDefault(parameterIndex); if (newParameter == null || newParameter.Identifier.IsMissing) { return argumentNode; } return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier))); }); } private static int TryDetermineParameterIndex(NameColonSyntax argumentNameColon, IMethodSymbol method) { var name = argumentNameColon.Name.Identifier.ValueText; return method.Parameters.IndexOf(p => p.Name == name); } private static EqualsValueClauseSyntax GetDefaultValue(IParameterSymbol parameter) => SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_local_function, createChangedDocument, CSharpAnalyzersResources.Use_local_function) { } } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Syntax/Syntax/ChildSyntaxListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ChildSyntaxListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList), default(ChildSyntaxList)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1), new ChildSyntaxList(node1)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList.Reversed), default(ChildSyntaxList.Reversed)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1).Reverse(), new ChildSyntaxList(node1).Reverse()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ChildSyntaxListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList), default(ChildSyntaxList)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1), new ChildSyntaxList(node1)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList.Reversed), default(ChildSyntaxList.Reversed)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1).Reverse(), new ChildSyntaxList(node1).Reverse()); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Symbol/Compilation/GetSemanticInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class GetSemanticInfoTests : SemanticModelTestBase { [WorkItem(544320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544320")] [Fact] public void TestBug12592() { var text = @" class B { public B(int x = 42) {} } class D : B { public D(int y) : base(/*<bind>*/x/*</bind>*/: y) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Parameter, sym.Symbol.Kind); Assert.Equal("x", sym.Symbol.Name); } [WorkItem(541948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541948")] [Fact] public void DelegateArgumentType() { var text = @"using System; delegate void MyEvent(); class Test { event MyEvent Clicked; void Handler() { } public void Run() { Test t = new Test(); t.Clicked += new MyEvent(/*<bind>*/Handler/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [WorkItem(541949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541949")] [Fact] public void LambdaWithParenthesis_BindOutsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = /*<bind>*/( delegate() { return 0; } )/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact] public void LambdaWithParenthesis_BindInsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = (/*<bind>*/ delegate() { return 0; }/*</bind>*/) ; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [Fact, WorkItem(528656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528656")] public void SemanticInfoForInvalidExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/ delegate * delegate /*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Null(sym.Symbol); } [WorkItem(541973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541973")] [Fact] public void LambdaAsAttributeArgumentErr() { var text = @"using System; delegate void D(); class MyAttr: Attribute { public MyAttr(D d) { } } [MyAttr((D)/*<bind>*/delegate { }/*</bind>*/)] // CS0182 public class A { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ClassifyConversionImplicit() { var text = @"using System; enum E { One, Two, Three } public class Test { static byte[] ary; static int Main() { // Identity ary = new byte[3]; // ImplicitConstant ary[0] = 0x0F; // ImplicitNumeric ushort ret = ary[0]; // ImplicitReference Test obj = null; // Identity obj = new Test(); // ImplicitNumeric obj.M(ary[0]); // boxing object box = -1; // ImplicitEnumeration E e = 0; // Identity E e2 = E.Two; // bind 'Two' return (int)ret; } void M(ulong p) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[1] as TypeDeclarationSyntax; Assert.Equal(3, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(10, mainStats.Count); // ary = new byte[3]; var v1 = (mainStats[0] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v1.Kind()); ConversionTestHelper(model, (v1 as AssignmentExpressionSyntax).Right, ConversionKind.Identity, ConversionKind.Identity); // ary[0] = 0x0F; var v2 = (mainStats[1] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitConstant, ConversionKind.ExplicitNumeric); // ushort ret = ary[0]; var v3 = (mainStats[2] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v3[0].Initializer.Value, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object obj01 = null; var v4 = (mainStats[3] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitReference, ConversionKind.NoConversion); // obj.M(ary[0]); var v6 = (mainStats[5] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.InvocationExpression, v6.Kind()); var v61 = (v6 as InvocationExpressionSyntax).ArgumentList.Arguments; ConversionTestHelper(model, v61[0].Expression, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object box = -1; var v7 = (mainStats[6] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v7[0].Initializer.Value, ConversionKind.Boxing, ConversionKind.Boxing); // E e = 0; var v8 = (mainStats[7] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v8[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E e2 = E.Two; var v9 = (mainStats[8] as LocalDeclarationStatementSyntax).Declaration.Variables; var v9val = (MemberAccessExpressionSyntax)(v9[0].Initializer.Value); var v9right = v9val.Name; ConversionTestHelper(model, v9right, ConversionKind.Identity, ConversionKind.Identity); } private void TestClassifyConversionBuiltInNumeric(string from, string to, ConversionKind ck) { const string template = @" class C {{ static void Goo({1} v) {{ }} static void Main() {{ {0} v = default({0}); Goo({2}v); }} }} "; var isExplicitConversion = ck == ConversionKind.ExplicitNumeric; var source = string.Format(template, from, to, isExplicitConversion ? "(" + to + ")" : ""); var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var c = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; var main = (MethodDeclarationSyntax)c.Members[1]; var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)main.Body.Statements[1]).Expression; var arg = call.ArgumentList.Arguments[0].Expression; if (isExplicitConversion) { ConversionTestHelper(model, ((CastExpressionSyntax)arg).Expression, model.GetTypeInfo(arg).ConvertedType, ck); } else { ConversionTestHelper(model, arg, ck, ck); } } [Fact] public void ClassifyConversionBuiltInNumeric() { const ConversionKind ID = ConversionKind.Identity; const ConversionKind IN = ConversionKind.ImplicitNumeric; const ConversionKind XN = ConversionKind.ExplicitNumeric; var types = new[] { "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char", "float", "double", "decimal" }; var conversions = new ConversionKind[,] { // to sb b s us i ui l ul c f d m // from /* sb */ { ID, XN, IN, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* b */ { XN, ID, IN, IN, IN, IN, IN, IN, XN, IN, IN, IN }, /* s */ { XN, XN, ID, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* us */ { XN, XN, XN, ID, IN, IN, IN, IN, XN, IN, IN, IN }, /* i */ { XN, XN, XN, XN, ID, XN, IN, XN, XN, IN, IN, IN }, /* ui */ { XN, XN, XN, XN, XN, ID, IN, IN, XN, IN, IN, IN }, /* l */ { XN, XN, XN, XN, XN, XN, ID, XN, XN, IN, IN, IN }, /* ul */ { XN, XN, XN, XN, XN, XN, XN, ID, XN, IN, IN, IN }, /* c */ { XN, XN, XN, IN, IN, IN, IN, IN, ID, IN, IN, IN }, /* f */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, IN, XN }, /* d */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, XN }, /* m */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID } }; for (var from = 0; from < types.Length; from++) { for (var to = 0; to < types.Length; to++) { TestClassifyConversionBuiltInNumeric(types[from], types[to], conversions[from, to]); } } } [WorkItem(527486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527486")] [Fact] public void ClassifyConversionExplicit() { var text = @"using System; public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // Cast y = (uint) x; // Boxing obj01 = x; // Cast x = (int)obj01; // NoConversion obj02 = (Test)obj01; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = (uint) x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v1 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_UInt32), ConversionKind.ExplicitNumeric); // obj01 = x; var v2 = (mainStats[2] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, comp.GetSpecialType(SpecialType.System_Object), ConversionKind.Boxing); // x = (int)obj01; var v3 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v3 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_Int32), ConversionKind.Unboxing); // obj02 = (Test)obj01; var tsym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault(); var v4 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v4 as CastExpressionSyntax).Expression, tsym, ConversionKind.ExplicitReference); } [Fact] public void DiagnosticsInStages() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { // ExplicitReference -> CS0266 obj02 = obj01; } binding error; parse err } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(4, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(2, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(1, errs.Count()); } [Fact] public void DiagnosticsFilteredWithPragmas() { var text = @" public class Test { #pragma warning disable 1633 #pragma xyzzy whatever #pragma warning restore 1633 } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); } [Fact] public void ClassifyConversionExplicitNeg() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // ExplicitNumeric - CS0266 y = x; // Boxing obj01 = x; // unboxing - CS0266 x = obj01; // ExplicitReference -> CS0266 obj02 = obj01; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v1, ConversionKind.ExplicitNumeric, ConversionKind.ExplicitNumeric); // x = obj01; var v2 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v2, ConversionKind.Unboxing, ConversionKind.Unboxing); // obj02 = obj01; var v3 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v3, ConversionKind.ExplicitReference, ConversionKind.ExplicitReference); // CC var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(0, errs.Count()); } [WorkItem(527767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527767")] [Fact] public void ClassifyConversionNullable() { var text = @"using System; public class Test { static void Main() { // NullLiteral sbyte? nullable = null; // ImplicitNullable uint? nullable01 = 100; ushort localVal = 123; // ImplicitNullable nullable01 = localVal; E e = 0; E? en = 0; // Oddly enough, C# classifies this as an implicit enumeration conversion. } } enum E { zero, one } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(1, testClass.Members.Count); var mainMethod = testClass.Members[0] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(6, mainStats.Count); // sbyte? nullable = null; var v1 = (mainStats[0] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v1[0].Initializer.Value, ConversionKind.NullLiteral, ConversionKind.NoConversion); // uint? nullable01 = 100; var v2 = (mainStats[1] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v2[0].Initializer.Value, ConversionKind.ImplicitNullable, ConversionKind.ExplicitNullable); // nullable01 = localVal; var v3 = (mainStats[3] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v3.Kind()); ConversionTestHelper(model, (v3 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitNullable, ConversionKind.ImplicitNullable); // E e = 0; var v4 = (mainStats[4] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E? en = 0; var v5 = (mainStats[5] as LocalDeclarationStatementSyntax).Declaration.Variables; // Bug#5035 (ByDesign): Conversion from literal 0 to nullable enum is Implicit Enumeration (not ImplicitNullable). Conversion from int to nullable enum is Explicit Nullable. ConversionTestHelper(model, v5[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitNullable); } [Fact, WorkItem(543994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543994")] public void ClassifyConversionImplicitUserDef() { var text = @"using System; class MyClass { public static bool operator true(MyClass p) { return true; } public static bool operator false(MyClass p) { return false; } public static MyClass operator &(MyClass mc1, MyClass mc2) { return new MyClass(); } public static int Main() { var cls1 = new MyClass(); var cls2 = new MyClass(); if (/*<bind0>*/cls1/*</bind0>*/) return 0; if (/*<bind1>*/cls1 && cls2/*</bind1>*/) return 1; return 2; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var expr2 = exprs.Last(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // It was ImplicitUserDef -> Design Meeting resolution: not expose op_True|False as conversion through API var impconv = model.GetConversion(expr1); Assert.Equal(Conversion.Identity, impconv); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.Equal("Identity", conv.ToString()); conv = model.ClassifyConversion(expr2, info.ConvertedType); CheckIsAssignableTo(model, expr2); Assert.Equal(impconv, conv); } [Fact, WorkItem(1019372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019372")] public void ClassifyConversionImplicitUserDef02() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { int? i = /*<bind0>*/this/*</bind0>*/; } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var impconv = model.GetConversion(expr1); Assert.True(impconv.IsImplicit); Assert.True(impconv.IsUserDefined); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.True(conv.IsImplicit); Assert.True(conv.IsUserDefined); } private void CheckIsAssignableTo(SemanticModel model, ExpressionSyntax syntax) { var info = model.GetTypeInfo(syntax); var conversion = info.Type != null && info.ConvertedType != null ? model.Compilation.ClassifyConversion(info.Type, info.ConvertedType) : Conversion.NoConversion; Assert.Equal(conversion.IsImplicit, model.Compilation.HasImplicitConversion(info.Type, info.ConvertedType)); } [Fact, WorkItem(544151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544151")] public void PublicViewOfPointerConversions() { ValidateConversion(Conversion.PointerToVoid, ConversionKind.ImplicitPointerToVoid); ValidateConversion(Conversion.NullToPointer, ConversionKind.ImplicitNullToPointer); ValidateConversion(Conversion.PointerToPointer, ConversionKind.ExplicitPointerToPointer); ValidateConversion(Conversion.IntegerToPointer, ConversionKind.ExplicitIntegerToPointer); ValidateConversion(Conversion.PointerToInteger, ConversionKind.ExplicitPointerToInteger); ValidateConversion(Conversion.IntPtr, ConversionKind.IntPtr); } #region "Conversion helper" private void ValidateConversion(Conversion conv, ConversionKind kind) { Assert.Equal(conv.Kind, kind); switch (kind) { case ConversionKind.NoConversion: Assert.False(conv.Exists); Assert.False(conv.IsImplicit); Assert.False(conv.IsExplicit); break; case ConversionKind.Identity: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsIdentity); break; case ConversionKind.ImplicitNumeric: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ImplicitEnumeration: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ImplicitNullable: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.NullLiteral: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullLiteral); break; case ConversionKind.ImplicitReference: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Boxing: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsBoxing); break; case ConversionKind.ImplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ExplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsExplicit); Assert.False(conv.IsImplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ImplicitConstant: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsConstantExpression); break; case ConversionKind.ImplicitUserDefined: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.AnonymousFunction: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsAnonymousFunction); break; case ConversionKind.MethodGroup: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsMethodGroup); break; case ConversionKind.ExplicitNumeric: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ExplicitEnumeration: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ExplicitNullable: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.ExplicitReference: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Unboxing: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUnboxing); break; case ConversionKind.ExplicitUserDefined: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.ImplicitNullToPointer: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ImplicitPointerToVoid: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitIntegerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToInteger: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.IntPtr: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.False(conv.IsPointer); Assert.True(conv.IsIntPtr); break; } } /// <summary> /// /// </summary> /// <param name="semanticModel"></param> /// <param name="expr"></param> /// <param name="ept1">expr -> TypeInParent</param> /// <param name="ept2">Type(expr) -> TypeInParent</param> private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ConversionKind ept1, ConversionKind ept2) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var conv = semanticModel.GetConversion(expr); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, info.ConvertedType); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(ept1, act1.Kind); ValidateConversion(act1, ept1); ValidateConversion(act1, conv.Kind); if (ept2 == ConversionKind.NoConversion) { Assert.Null(info.Type); } else { Assert.NotNull(info.Type); var act2 = semanticModel.Compilation.ClassifyConversion(info.Type, info.ConvertedType); Assert.Equal(ept2, act2.Kind); ValidateConversion(act2, ept2); } } private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ITypeSymbol expsym, ConversionKind expkind) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, expsym); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(expkind, act1.Kind); ValidateConversion(act1, expkind); } #endregion [Fact] public void EnumOffsets() { // sbyte EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 1))); EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 2))); EnumOffset(ConstantValue.Create((sbyte)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(-1))); EnumOffset(ConstantValue.Create((sbyte)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(1))); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)sbyte.MaxValue)); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // byte EnumOffset(ConstantValue.Create((byte)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)1)); EnumOffset(ConstantValue.Create((byte)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)2)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)byte.MaxValue)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // short EnumOffset(ConstantValue.Create((short)short.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 1))); EnumOffset(ConstantValue.Create((short)short.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 2))); EnumOffset(ConstantValue.Create((short)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(-1))); EnumOffset(ConstantValue.Create((short)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(1))); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)short.MaxValue)); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ushort EnumOffset(ConstantValue.Create((ushort)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)1)); EnumOffset(ConstantValue.Create((ushort)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)2)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)ushort.MaxValue)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // int EnumOffset(ConstantValue.Create((int)int.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 1))); EnumOffset(ConstantValue.Create((int)int.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 2))); EnumOffset(ConstantValue.Create((int)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(-1))); EnumOffset(ConstantValue.Create((int)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(1))); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)int.MaxValue)); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // uint EnumOffset(ConstantValue.Create((uint)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)1)); EnumOffset(ConstantValue.Create((uint)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)2)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)uint.MaxValue)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // long EnumOffset(ConstantValue.Create((long)long.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 1))); EnumOffset(ConstantValue.Create((long)long.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 2))); EnumOffset(ConstantValue.Create((long)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(-1))); EnumOffset(ConstantValue.Create((long)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(1))); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)long.MaxValue)); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ulong EnumOffset(ConstantValue.Create((ulong)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)1)); EnumOffset(ConstantValue.Create((ulong)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)2)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)ulong.MaxValue)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); } private void EnumOffset(ConstantValue constantValue, uint offset, EnumOverflowKind expectedOverflowKind, ConstantValue expectedValue) { ConstantValue actualValue; var actualOverflowKind = EnumConstantHelper.OffsetValue(constantValue, offset, out actualValue); Assert.Equal(expectedOverflowKind, actualOverflowKind); Assert.Equal(expectedValue, actualValue); } [Fact] public void TestGetSemanticInfoInParentInIf() { var compilation = CreateCompilation(@" class C { void M(int x) { if (x == 10) {} } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var ifStatement = (IfStatementSyntax)methodDecl.Body.Statements[0]; var condition = ifStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.Type.Name); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [Fact] public void TestGetSemanticInfoInParentInFor() { var compilation = CreateCompilation(@" class C { void M(int x) { for (int i = 0; i < 10; i = i + 1) { } } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var forStatement = (ForStatementSyntax)methodDecl.Body.Statements[0]; var condition = forStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.ConvertedType.Name); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")] [Fact] public void NoMembersForVoidReturnType() { var text = @" class C { void M() { /*<bind>*/System.Console.WriteLine()/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); IMethodSymbol methodSymbol = (IMethodSymbol)bindInfo.Symbol; ITypeSymbol returnType = methodSymbol.ReturnType; var symbols = model.LookupSymbols(0, returnType); Assert.Equal(0, symbols.Length); } [WorkItem(540767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540767")] [Fact] public void BindIncompleteVarDeclWithDoKeyword() { var code = @" class Test { static int Main(string[] args) { do"; var compilation = CreateCompilation(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxList = GetExprSyntaxList(tree); Assert.Equal(6, exprSyntaxList.Count); // Note the omitted array size expression in "string[]" Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[4].Kind()); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[5].Kind()); Assert.Equal("", exprSyntaxList[4].ToFullString()); Assert.Equal("", exprSyntaxList[5].ToFullString()); var exprSyntaxToBind = exprSyntaxList[exprSyntaxList.Count - 2]; model.GetSemanticInfoSummary(exprSyntaxToBind); } [Fact] public void TestBindBaseConstructorInitializer() { var text = @" class C { C() : base() { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("System.Object..ctor()", baseConstructor.ToTestDisplayString()); } [Fact] public void TestBindThisConstructorInitializer() { var text = @" class C { C() : this(1) { } C(int x) { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("C..ctor(System.Int32 x)", baseConstructor.ToTestDisplayString()); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void BindThisStaticConstructorInitializer() { var text = @" class MyClass { static MyClass() : this() { intI = 2; } public MyClass() { } static int intI = 1; } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var invokedConstructor = (IMethodSymbol)bindInfo.Symbol; Assert.Equal(MethodKind.Constructor, invokedConstructor.MethodKind); Assert.Equal("MyClass..ctor()", invokedConstructor.ToTestDisplayString()); } [WorkItem(541053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541053")] [Fact] public void CheckAndAdjustPositionOutOfRange() { var text = @" using System; > 1 "; var tree = Parse(text, options: TestOptions.Script); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); Assert.NotEqual(0, root.SpanStart); var stmt = (GlobalStatementSyntax)root.Members.Single(); var expr = ((ExpressionStatementSyntax)stmt.Statement).Expression; Assert.Equal(SyntaxKind.GreaterThanExpression, expr.Kind()); var info = model.GetSemanticInfoSummary(expr); Assert.Equal(SpecialType.System_Boolean, info.Type.SpecialType); } [Fact] public void AddAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += /*<bind>*/value/*</bind>*/; } remove { e -= value; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventAdd, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void RemoveAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += value; } remove { e -= /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventRemove, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void FieldLikeEventInitializer() { var text = @" class C { event System.Action E = /*<bind>*/new System.Action(() => { })/*</bind>*/; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); } [Fact] public void FieldLikeEventInitializer2() { var text = @" class C { event System.Action E = new /*<bind>*/System.Action/*</bind>*/(() => { }); } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Null(bindInfo.Type); Assert.Equal(systemActionType, bindInfo.Symbol); } [Fact] public void CustomEventAccess() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void FieldLikeEventAccess() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void CustomEventAssignmentOperator() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void FieldLikeEventAssignmentOperator() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void CustomEventMissingAssignmentOperator() { var text = @" class C { event System.Action E { /*add { }*/ remove { } } //missing add void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); } private static INamedTypeSymbol GetSystemActionType(CSharpCompilation comp) { return GetSystemActionType((Compilation)comp); } private static INamedTypeSymbol GetSystemActionType(Compilation comp) { return (INamedTypeSymbol)comp.GlobalNamespace.GetMember<INamespaceSymbol>("System").GetMembers("Action").Where(s => !((INamedTypeSymbol)s).IsGenericType).Single(); } [Fact] public void IndexerAccess() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); Assert.Equal(indexerSymbol, bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessOverloadResolutionFailure() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol1 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); var indexerSymbol2 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 2).Single().GetPublicSymbol(); var candidateIndexers = ImmutableArray.Create<ISymbol>(indexerSymbol1, indexerSymbol2); Assert.Null(bindInfo.Symbol); Assert.True(bindInfo.CandidateSymbols.SetEquals(candidateIndexers, EqualityComparer<ISymbol>.Default)); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); //still have the type since all candidates agree Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessNoIndexers() { var text = @" class C { void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(TypeKind.Error, bindInfo.Type.TypeKind); Assert.Equal(TypeKind.Struct, bindInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess1() { var text = @" public class Test { public int Fld; public int Func() { return (int)(/*<bind>*/Fld<int>/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, bindInfo.CandidateReason); Assert.Equal(1, bindInfo.CandidateSymbols.Length); var candidate = bindInfo.CandidateSymbols.Single(); Assert.Equal(SymbolKind.Field, candidate.Kind); Assert.Equal("Fld", candidate.Name); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess2() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld</*<bind>*/Test/*</bind>*/>); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal("Test", symbol.Name); } [WorkItem(528785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528785")] [Fact] public void TopLevelIndexer() { var text = @" this[double E] { get { return /*<bind>*/E/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); } [WorkItem(542360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542360")] [Fact] public void TypeAndMethodHaveSameTypeParameterName() { var text = @" interface I<T> { void Goo<T>(); } class A<T> : I<T> { void I</*<bind>*/T/*</bind>*/>.Goo<T>() { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("T", symbol.Name); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("A"), symbol.ContainingSymbol); //from the type, not the method } [WorkItem(542436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542436")] [Fact] public void RecoveryFromBadNamespaceDeclaration() { var text = @"namespace alias:: using alias = /*<bind>*/N/*</bind>*/; namespace N { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); } /// Test that binding a local declared with var binds the same way when localSymbol.Type is called before BindVariableDeclaration. /// Assert occurs if the two do not compute the same type. [Fact] [WorkItem(542634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542634")] public void VarInitializedWithStaticType() { var text = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static string xunit = " + "@" + @"..\..\Closed\Tools\xUnit\xunit.console.x86.exe" + @"; static string test = " + @"Roslyn.VisualStudio.Services.UnitTests.dll" + @"; static string commandLine = test" + @" /html log.html" + @"; static void Main(string[] args) { var options = CreateOptions(); /*<bind>*/Parallel/*</bind>*/.For(0, 100, RunTest, options); } private static Parallel CreateOptions() { var result = new ParallelOptions(); } private static void RunTest(int i) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); // Bind Parallel from line Parallel.For(0, 100, RunTest, options); // This will implicitly bind "var" to determine type of options. // This calls LocalSymbol.GetType var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var varIdentifier = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().DescendantNodes().First(n => n.ToString() == "var"); // var from line var options = CreateOptions; // Explicitly bind "var". // This path calls BindvariableDeclaration. bindInfo = model.GetSemanticInfoSummary(varIdentifier); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerParameter() { var text = @" class C { int this[int x] { get { return /*<bind>*/x/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "x"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerValueParameter() { var text = @" class C { int this[int x] { set { x = /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("value", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "value"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542777")] [Fact] public void IndexerThisParameter() { var text = @" class C { int this[int x] { set { System.Console.Write(/*<bind>*/this/*</bind>*/); } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ThisExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("this", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); } [WorkItem(542592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542592")] [Fact] public void TypeParameterParamsParameter() { var text = @" class Test<T> { public void Method(params T arr) { } } class Program { static void Main(string[] args) { new Test<int[]>()./*<bind>*/Method/*</bind>*/(new int[][] { }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); var candidate = (IMethodSymbol)bindInfo.CandidateSymbols.Single(); Assert.Equal("void Test<System.Int32[]>.Method(params System.Int32[] arr)", candidate.ToTestDisplayString()); Assert.Equal(TypeKind.Array, candidate.Parameters.Last().Type.TypeKind); Assert.Equal(TypeKind.TypeParameter, ((IMethodSymbol)candidate.OriginalDefinition).Parameters.Last().Type.TypeKind); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void ParameterDefaultValues() { var text = @" struct S { void M( int i = 1, string str = ""hello"", object o = null, S s = default(S)) { /*<bind>*/M/*</bind>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var method = (IMethodSymbol)bindInfo.Symbol; Assert.NotNull(method); var parameters = method.Parameters; Assert.Equal(4, parameters.Length); Assert.True(parameters[0].HasExplicitDefaultValue); Assert.Equal(1, parameters[0].ExplicitDefaultValue); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal("hello", parameters[1].ExplicitDefaultValue); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultValue); Assert.True(parameters[3].HasExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultValue); } [WorkItem(542764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542764")] [Fact] public void UnboundGenericTypeArity() { var text = @" class C<T, U, V> { void M() { System.Console.Write(typeof(/*<bind>*/C<,,>/*</bind>*/)); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var nameSyntaxToBind = (SimpleNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, nameSyntaxToBind.Kind()); Assert.Equal(3, nameSyntaxToBind.Arity); var bindInfo = model.GetSymbolInfo(nameSyntaxToBind); var type = (INamedTypeSymbol)bindInfo.Symbol; Assert.NotNull(type); Assert.True(type.IsUnboundGenericType); Assert.Equal(3, type.Arity); Assert.Equal("C<,,>", type.ToTestDisplayString()); } [Fact] public void GetType_VoidArray() { var text = @" class C { void M() { var x = typeof(/*<bind>*/System.Void[]/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ArrayType, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var arrayType = (IArrayTypeSymbol)bindInfo.Symbol; Assert.NotNull(arrayType); Assert.Equal("System.Void[]", arrayType.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance1() { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public class C<T> where T : IA, IB // can find IA.P in two different ways { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance2() //add hiding member in derived interface { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IA, IB { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance3() //reverse order of interface list (shouldn't matter) { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IB, IA { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance4() //Two interfaces with a common base { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public interface IC : IA { } public class C<T> where T : IB, IC { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup1() { var types = @" public interface IA { object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA", "P", out _); Assert.Equal("System.Object IA.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup2() { var types = @" public interface IA { object P { get; } } public interface IB { object P { get; } } "; ITypeParameterSymbol typeParameter; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out typeParameter); Assert.True(members.SetEquals(typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics().Select(i => i.GetMember<IPropertySymbol>("P")))); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup3() { var types = @" public interface IA { object P { get; } } public interface IB : IA { new object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out _); Assert.Equal("System.Object IB.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup4() { var types = @" public interface IA { object P { get; } } public class D { public object P { get; set; } } "; var members = LookupTypeParameterMembers(types, "D, IA", "P", out _); Assert.Equal("System.Object D.P { get; set; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup5() { var types = @" public interface IA { void M(); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.Equal("void IA.M()", members.Single().ToTestDisplayString()); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void D.M()" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup6() { var types = @" public interface IA { void M(); void M(int x); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void IA.M(System.Int32 x)" })); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void D.M()", "void IA.M()", "void IA.M(System.Int32 x)" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup7() { var types = @" public interface IA { string ToString(); } public class D { public new string ToString() { return null; } } "; var members = LookupTypeParameterMembers(types, "IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String IA.ToString()" })); members = LookupTypeParameterMembers(types, "D, IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String D.ToString()", "System.String IA.ToString()" })); } private IEnumerable<ISymbol> LookupTypeParameterMembers(string types, string constraints, string memberName, out ITypeParameterSymbol typeParameter) { var template = @" {0} public class C<T> where T : {1} {{ void M() {{ System.Console.WriteLine(/*<bind>*/default(T)/*</bind>*/); }} }} "; var tree = Parse(string.Format(template, types, constraints)); var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var classC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); typeParameter = classC.TypeParameters.Single(); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.DefaultExpression, exprSyntaxToBind.Kind()); return model.LookupSymbols(exprSyntaxToBind.SpanStart, typeParameter, memberName); } [WorkItem(542966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542966")] [Fact] public async Task IndexerMemberRaceAsync() { var text = @" using System; interface IA { [System.Runtime.CompilerServices.IndexerName(""Goo"")] string this[int index] { get; } } class A : IA { public virtual string this[int index] { get { return """"; } } string IA.this[int index] { get { return """"; } } } class B : A, IA { public override string this[int index] { get { return """"; } } } class Program { public static void Main(string[] args) { IA x = new B(); Console.WriteLine(x[0]); } } "; TimeSpan timeout = TimeSpan.FromSeconds(2); for (int i = 0; i < 20; i++) { var comp = CreateCompilation(text); var task1 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers()); var task2 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMembers()); if (i % 2 == 0) { task1.Start(); task2.Start(); } else { task2.Start(); task1.Start(); } comp.VerifyDiagnostics(); await Task.WhenAll(task1, task2); } } [Fact] public void ImplicitDeclarationMultipleDeclarators() { var text = @" using System.IO; class C { static void Main() { /*<bind>*/var a = new StreamWriter(""""), b = new StreamReader("""")/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (8,19): error CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/var a = new StreamWriter(""), b = new StreamReader("")/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")").WithLocation(8, 19) ); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var typeInfo = model.GetSymbolInfo(expr); // the type info uses the type inferred for the first declared local Assert.Equal("System.IO.StreamWriter", typeInfo.Symbol.ToTestDisplayString()); } [WorkItem(543169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543169")] [Fact] public void ParameterOfLambdaPassedToOutParameter() { var text = @" using System.Linq; class D { static void Main(string[] args) { string[] str = new string[] { }; label1: var s = str.Where(out /*<bind>*/x/*</bind>*/ => { return x == ""1""; }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parameterSymbol = model.GetDeclaredSymbol(lambdaSyntax.Parameter); Assert.NotNull(parameterSymbol); Assert.Equal("x", parameterSymbol.Name); Assert.Equal(MethodKind.AnonymousFunction, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")] [Fact] public void MemberAccessExpressionResults() { var text = @" class C { public static int A; public static byte B() { return 3; } public static string D { get; set; } static void Main(string[] args) { /*<bind0>*/C.A/*</bind0>*/; /*<bind1>*/C.B/*</bind1>*/(); /*<bind2>*/C.D/*</bind2>*/; /*<bind3>*/C.B()/*</bind3>*/; int goo = /*<bind4>*/C.B()/*</bind4>*/; goo = /*<bind5>*/C.B/*</bind5>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); for (int i = 0; i < exprs.Count; i++) { var expr = exprs[i]; var symbolInfo = model.GetSymbolInfo(expr); Assert.NotNull(symbolInfo.Symbol); var typeInfo = model.GetTypeInfo(expr); switch (i) { case 0: Assert.Equal("A", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; case 1: case 5: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.Null(typeInfo.Type); break; case 2: Assert.Equal("D", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()); break; case 3: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Byte", typeInfo.ConvertedType.ToTestDisplayString()); break; case 4: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; } // switch } } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForUncheckedExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/unchecked(42 + 42.1)/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Double System.Double.op_Addition(System.Double left, System.Double right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Double, info.Type.SpecialType); Assert.Equal(SpecialType.System_Double, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForCheckedExpression() { var text = @" class Program { public static int Add(int a, int b) { return /*<bind>*/checked(a+b)/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void CheckedUncheckedExpression() { var text = @" class Test { public void F() { int y = /*<bind>*/(checked(unchecked((1))))/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact] public void SymbolInfoForImplicitOperatorParameter() { var text = @" class Program { public Program(string s) { } public static implicit operator Program(string str) { return new Program(/*<bind>*/str/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetSymbolInfo(expr); var symbol = info.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)symbol.ContainingSymbol).MethodKind); } [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] [WorkItem(543560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543560")] [Fact] public void BrokenPropertyDeclaration() { var source = @" using System; Class Program // this will get a Property declaration ... *sigh* { static void Main(string[] args) { Func<int, int> f = /*<bind0>*/x/*</bind0>*/ => x + 1; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().First(); var declaredSymbol = model.GetDeclaredSymbol(expr); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedLogicalOperator() { var text = @" class C { public static C operator &(C c1, C c2) { return c1 ?? c2; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 && c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.BitwiseAndOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedUnaryOperator() { var text = @" class C { public static C operator+(C c1) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.UnaryPlusOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedExplicitConversion() { var text = @" class C { public static explicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ExplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedImplicitConversion() { var text = @" class C { public static implicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ImplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedTrueOperator() { var text = @" class C { public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c = new C(); if (/*<bind>*/c/*</bind>*/) { } } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var type = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); var symbol = symbolInfo.Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("c", symbol.Name); Assert.Equal(type, ((ILocalSymbol)symbol).Type); var typeInfo = model.GetTypeInfo(expr); Assert.Equal(type, typeInfo.Type); Assert.Equal(type, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(Conversion.Identity, conv); Assert.False(model.GetConstantValue(expr).HasValue); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedIncrement() { var text = @" class C { public static C operator ++(C c) { return c; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.IncrementOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedCompoundAssignment() { var text = @" class C { public static C operator +(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); /*<bind>*/c1 += c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } private void CheckOperatorSemanticInfo(string text, string operatorName) { var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operatorSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>(operatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); var method = (IMethodSymbol)symbolInfo.Symbol; var returnType = method.ReturnType; var typeInfo = model.GetTypeInfo(expr); Assert.Equal(returnType, typeInfo.Type); Assert.Equal(returnType, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.False(model.GetConstantValue(expr).HasValue); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailure() { var text = @" struct S { public static explicit operator S(string s) { return default(S); } public static explicit operator S(System.Text.StringBuilder s) { return default(S); } static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(conversions, EqualityComparer<ISymbol>.Default)); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailureEmpty() { var text = @" struct S { static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversions.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit UnaryOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class UnaryOperator op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } // Differs only by return type .method public hidebysig specialname static string op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { UnaryOperator u1 = new UnaryOperator(); UnaryOperator u2 = /*<bind>*/+u1/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("UnaryOperator").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit IncrementOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class IncrementOperator op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname static string op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { IncrementOperator i1 = new IncrementOperator(); IncrementOperator i2 = /*<bind>*/i1++/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IncrementOperator").GetMembers(WellKnownMemberNames.IncrementOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.IncrementOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(529158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529158")] [Fact] public void MethodGroupForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, int i) { return c1; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName).Cast<IMethodSymbol>(); var operatorSymbol = operators.Where(method => method.Parameters[0].Type.Equals(method.Parameters[1].Type, SymbolEqualityComparer.ConsiderEverything)).Single(); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); // NOTE: This check captures, rather than enforces, the current behavior (i.e. feel free to change it). var memberGroup = model.GetMemberGroup(expr); Assert.Equal(0, memberGroup.Length); } [Fact] public void CacheDuplicates() { var text = @" class C { static void Main() { long l = /*<bind>*/(long)1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); bool sawWrongConversionKind = false; ThreadStart ts = () => sawWrongConversionKind |= ConversionKind.Identity != model.GetConversion(expr).Kind; Thread[] threads = new Thread[4]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(ts); } foreach (Thread t in threads) { t.Start(); } foreach (Thread t in threads) { t.Join(); } Assert.False(sawWrongConversionKind); } [WorkItem(543674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543674")] [Fact()] public void SemanticInfo_NormalVsLiftedUserDefinedImplicitConversion() { string text = @" using System; struct G { } struct L { public static implicit operator G(L l) { return default(G); } } class Z { public static void Main() { MNG(/*<bind>*/default(L)/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); // Here we have a situation where Roslyn deliberately violates the specification in order // to be compatible with the native compiler. // // The specification states that there are two applicable candidates: We can use // the "lifted" operator from L? to G?, or we can use the unlifted operator // from L to G, and then convert the G that comes out the back end to G?. // The specification says that the second conversion is the better conversion. // Therefore, the conversion on the "front end" should be an identity conversion, // and the conversion on the "back end" of the user-defined conversion should // be an implicit nullable conversion. // // This is not at all what the native compiler does, and we match the native // compiler behavior. The native compiler says that there is a "half lifted" // conversion from L-->G?, and that this is the winner. Therefore the conversion // "on the back end" of the user-defined conversion is in fact an *identity* // conversion, even though obviously we are going to have to // do code generation as though it was an implicit nullable conversion. Assert.Equal(ConversionKind.Identity, conversion.UserDefinedFromConversion.Kind); Assert.Equal(ConversionKind.Identity, conversion.UserDefinedToConversion.Kind); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [WorkItem(543715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543715")] [Fact] public void SemanticInfo_NormalVsLiftedUserDefinedConversion_ImplicitConversion() { string text = @" using System; struct G {} struct M { public static implicit operator G(M m) { System.Console.WriteLine(1); return default(G); } public static implicit operator G(M? m) {System.Console.WriteLine(2); return default(G); } } class Z { public static void Main() { M? m = new M(); MNG(/*<bind>*/m/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion.Kind); // Dev10 violates the spec for finding the most specific operator for an implicit user-defined conversion. // SPEC: • Find the most specific conversion operator: // SPEC: (a) If U contains exactly one user-defined conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (b) Otherwise, if U contains exactly one lifted conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (c) Otherwise, the conversion is ambiguous and a compile-time error occurs. // In this test we try to classify conversion from M? to G?. // 1) Classify conversion establishes that SX: M? and TX: G?. // 2) Most specific conversion operator from M? to G?: // (a) does not hold here as neither of the implicit operators convert from M? to G? // (b) does hold here as the lifted form of "implicit operator G(M m)" converts from M? to G? // Hence "operator G(M m)" must be chosen in lifted form, but Dev10 chooses "G M.op_Implicit(System.Nullable<M> m)" in normal form. // We may want to maintain compatibility with Dev10. Assert.Equal("G M.op_Implicit(M? m)", conversion.MethodSymbol.ToTestDisplayString()); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [Fact] public void AmbiguousImplicitConversionOverloadResolution1() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void M(A a) { } static void M(object o) { } static void Main() { B b = new B(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (26,21): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void Test.M(A a)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("A", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.ImplicitUserDefined, argConversion.Kind); Assert.False(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void AmbiguousImplicitConversionOverloadResolution2() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void M(A a) { } static void M<T>(T t) { } static void Main() { B<A> b = new B<A>(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); // since no conversion is performed, the ambiguity doesn't matter var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void C.M<B<A>>(B<A> t)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B<A>", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("B<A>", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.Identity, argConversion.Kind); Assert.True(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void DefaultParameterLocalScope() { var source = @" public class A { static void Main(string[] args, int a = /*<bind>*/System/*</bind>*/.) { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("System", expr.ToString()); var info = model.GetSemanticInfoSummary(expr); //Shouldn't throw/assert Assert.Equal(SymbolKind.Namespace, info.Symbol.Kind); } [Fact] public void PinvokeSemanticModel() { var source = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""user32.dll"", CharSet = CharSet.Unicode, ExactSpelling = false, EntryPoint = ""MessageBox"")] public static extern int MessageBox(IntPtr hwnd, string t, string c, UInt32 t2); static void Main() { /*<bind>*/MessageBox(IntPtr.Zero, """", """", 1)/*</bind>*/; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("MessageBox(IntPtr.Zero, \"\", \"\", 1)", expr.ToString()); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("C.MessageBox(System.IntPtr, string, string, uint)", symbolInfo.Symbol.ToDisplayString()); var argTypeInfo = model.GetTypeInfo(expr.ArgumentList.Arguments.First().Expression); Assert.Equal("System.IntPtr", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("System.IntPtr", argTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void ImplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = 1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var conv = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, conv.Kind); } [Fact] public void ImplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Int64, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, castConversion.Kind); } [Fact] public void ExplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = (object)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Object, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, castConversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(literal, castTypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); } [Fact] public void ExplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (object)(long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast1 = (CastExpressionSyntax)literal.Parent; var cast1TypeInfo = model.GetTypeInfo(cast1); var cast1Conversion = model.GetConversion(cast1); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast1Conversion.Kind); // Note that this reflects the hypothetical conversion, not the cast in the code. Assert.Equal(ConversionKind.ImplicitNumeric, model.ClassifyConversion(literal, cast1TypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); var cast2 = (CastExpressionSyntax)cast1.Parent; var cast2TypeInfo = model.GetTypeInfo(cast2); var cast2Conversion = model.GetConversion(cast2); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast2Conversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(cast1, cast2TypeInfo.Type).Kind); CheckIsAssignableTo(model, cast1); } [WorkItem(545136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545136")] [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact()] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins. public void SpecialTypeInSourceAndMetadata() { var text = @" using System; namespace System { public struct Void { static void Main() { System./*<bind>*/Void/*</bind>*/.Equals(1, 1); } } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.Void", symbolInfo.Symbol.ToString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup1() { var text = @" using System; class C { static void M() { int here; } } "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup2() { var text = @" using System; class C { static void M() { int here; } static void M(int x) { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent1() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/ "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent2() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/[] "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup1() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = (Compilation)CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("IA").GetMember<IPropertySymbol>("P"), info.Symbol); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object Property P(x As Object, y As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } // There is no test analogous to UnambiguousMethodGroupWithoutBoundParent1 because // a.P does not yield a bound property group - it yields a bound indexer access // (i.e. it doesn't actually hit the code path that formerly contained the assert). //[WorkItem(15177)] //[Fact] //public void UnambiguousPropertyGroupWithoutBoundParent1() [WorkItem(546117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546117")] [ClrOnlyFact] public void UnambiguousPropertyGroupWithoutBoundParent2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { /*<bind>*/a.P/*</bind>*/[] "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.QualifiedName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544648")] [Fact] public void SpeculativelyBindExtensionMethod() { var source = @" using System; using System.Collections.Generic; using System.Reflection; static class Program { static void Main() { FieldInfo[] fields = typeof(Exception).GetFields(); Console.WriteLine(/*<bind>*/fields.Any((Func<FieldInfo, bool>)(field => field.IsStatic))/*</bind>*/); } static bool Any<T>(this IEnumerable<T> s, Func<T, bool> predicate) { return false; } static bool Any<T>(this ICollection<T> s, Func<T, bool> predicate) { return true; } } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var originalSyntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.InvocationExpression, originalSyntax.Kind()); var info1 = model.GetSymbolInfo(originalSyntax); var method1 = info1.Symbol as IMethodSymbol; Assert.NotNull(method1); Assert.Equal("System.Boolean System.Collections.Generic.ICollection<System.Reflection.FieldInfo>.Any<System.Reflection.FieldInfo>(System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", method1.ToTestDisplayString()); Assert.Same(method1.ReducedFrom.TypeParameters[0], method1.TypeParameters[0].ReducedFrom); Assert.Null(method1.ReducedFrom.TypeParameters[0].ReducedFrom); Assert.Equal("System.Boolean Program.Any<T>(this System.Collections.Generic.ICollection<T> s, System.Func<T, System.Boolean> predicate)", method1.ReducedFrom.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.ICollection<System.Reflection.FieldInfo>", method1.ReceiverType.ToTestDisplayString()); Assert.Equal("System.Reflection.FieldInfo", method1.GetTypeInferredDuringReduction(method1.ReducedFrom.TypeParameters[0]).ToTestDisplayString()); Assert.Throws<InvalidOperationException>(() => method1.ReducedFrom.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentNullException>(() => method1.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentException>(() => method1.GetTypeInferredDuringReduction( comp.Assembly.GlobalNamespace.GetMember<INamedTypeSymbol>("Program").GetMembers("Any"). Where((m) => (object)m != (object)method1.ReducedFrom).Cast<IMethodSymbol>().Single().TypeParameters[0])); Assert.Equal("Any", method1.Name); var reducedFrom1 = method1.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom1); Assert.Equal("System.Boolean Program.Any<System.Reflection.FieldInfo>(this System.Collections.Generic.ICollection<System.Reflection.FieldInfo> s, System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", reducedFrom1.ToTestDisplayString()); Assert.Equal("Program", reducedFrom1.ReceiverType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom1.Parameters[0].Type.OriginalDefinition).SpecialType); var speculativeSyntax = SyntaxFactory.ParseExpression("fields.Any((field => field.IsStatic))"); //cast removed Assert.Equal(SyntaxKind.InvocationExpression, speculativeSyntax.Kind()); var info2 = model.GetSpeculativeSymbolInfo(originalSyntax.SpanStart, speculativeSyntax, SpeculativeBindingOption.BindAsExpression); var method2 = info2.Symbol as IMethodSymbol; Assert.NotNull(method2); Assert.Equal("Any", method2.Name); var reducedFrom2 = method2.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom2); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom2.Parameters[0].Type.OriginalDefinition).SpecialType); Assert.Equal(reducedFrom1, reducedFrom2); Assert.Equal(method1, method2); } /// <summary> /// This test reproduces the issue we were seeing in DevDiv #13366: LocalSymbol.SetType was asserting /// because it was set to IEnumerable&lt;int&gt; before binding the declaration of x but to an error /// type after binding the declaration of x. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding1() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info0 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info0.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info0.Symbol).TypeArguments.Single().SpecialType); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } /// <summary> /// This test reverses the order of statement binding from NameConflictDuringLambdaBinding2 to confirm that /// the results are the same. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding2() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } [WorkItem(546263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546263")] [Fact] public void SpeculativeSymbolInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeSymbolInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Null(info.Symbol); } [WorkItem(530313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530313")] [Fact] public void SpeculativeTypeInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Equal(TypeInfo.None, info); } [WorkItem(546266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546266")] [Fact] public void SpeculativeTypeInfoForGenericNameSyntaxWithinTypeOfInsideAnonMethod() { var text = @" delegate void Del(); class C { public void M1() { Del d = delegate () { var v1 = typeof(S<,,,>); }; } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("S<,,,>", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<GenericNameSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void SemanticInfoForOmittedTypeArgumentInIncompleteMember() { var text = @" class Test { C<> "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSemanticInfoSummary(syntax); Assert.Null(info.Alias); Assert.Equal(CandidateReason.None, info.CandidateReason); Assert.True(info.CandidateSymbols.IsEmpty); Assert.False(info.ConstantValue.HasValue); Assert.Null(info.ConvertedType); Assert.Equal(Conversion.Identity, info.ImplicitConversion); Assert.False(info.IsCompileTimeConstant); Assert.True(info.MemberGroup.IsEmpty); Assert.True(info.MethodGroup.IsEmpty); Assert.Null(info.Symbol); Assert.Null(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void CollectionInitializerSpeculativeInfo() { var text = @" class Test { } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var speculativeSyntax = SyntaxFactory.ParseExpression("new List { 1, 2 }"); var initializerSyntax = speculativeSyntax.DescendantNodesAndSelf().OfType<InitializerExpressionSyntax>().Single(); var symbolInfo = model.GetSpeculativeSymbolInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); var typeInfo = model.GetSpeculativeTypeInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(TypeInfo.None, typeInfo); } [WorkItem(531362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531362")] [Fact] public void DelegateElementAccess() { var text = @" class C { void M(bool b) { System.Action o = delegate { if (b) { } } [1]; } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (6,27): error CS0021: Cannot apply indexing with [] to an expression of type 'anonymous method' // System.Action o = delegate { if (b) { } } [1]; Diagnostic(ErrorCode.ERR_BadIndexLHS, "delegate { if (b) { } } [1]").WithArguments("anonymous method")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last(id => id.Identifier.ValueText == "b"); var info = model.GetSymbolInfo(syntax); } [Fact] public void EnumBitwiseComplement() { var text = @" using System; enum Color { Red, Green, Blue } class C { static void Main() { Func<Color, Color> f2 = x => /*<bind>*/~x/*</bind>*/; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(syntax); var conv = model.GetConversion(syntax); Assert.Equal(TypeKind.Enum, info.Type.TypeKind); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(531534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531534")] [Fact] public void LambdaOutsideMemberModel() { var text = @" int P { badAccessorName { M(env => env); "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last(); var symbol = model.GetDeclaredSymbol(syntax); // Doesn't assert. Assert.Null(symbol); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void MemberOfInaccessibleType() { var text = @" class A { private class Nested { public class Another { } } } public class B : A { public Nested.Another a; } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var classAnother = classNested.GetMember<INamedTypeSymbol>("Another"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var fieldSyntax = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single(); var qualifiedSyntax = (QualifiedNameSyntax)fieldSyntax.Declaration.Type; var leftSyntax = qualifiedSyntax.Left; var rightSyntax = qualifiedSyntax.Right; var leftInfo = model.GetSymbolInfo(leftSyntax); Assert.Equal(CandidateReason.Inaccessible, leftInfo.CandidateReason); Assert.Equal(classNested, leftInfo.CandidateSymbols.Single()); var rightInfo = model.GetSymbolInfo(rightSyntax); Assert.Equal(CandidateReason.Inaccessible, rightInfo.CandidateReason); Assert.Equal(classAnother, rightInfo.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0060: Inconsistent accessibility: base type 'A' is less accessible than class 'B' // public class B : A Diagnostic(ErrorCode.ERR_BadVisBaseClass, "B").WithArguments("B", "A"), // (14,12): error CS0122: 'A.Nested' is inaccessible due to its protection level // public Nested.Another a; Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void NotReferencableMemberOfInaccessibleType() { var text = @" class A { private class Nested { public int P { get; set; } } } class B : A { int Test(Nested nested) { return nested.get_P(); } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var propertyP = classNested.GetMember<IPropertySymbol>("P"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccessSyntax = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessSyntax); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); Assert.Equal(propertyP.GetMethod, info.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0122: 'A.Nested' is inaccessible due to its protection level // int Test(Nested nested) Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested"), // (14,23): error CS0571: 'A.Nested.P.get': cannot explicitly call operator or accessor // return nested.get_P(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.Nested.P.get") ); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void AccessibleMemberOfInaccessibleType() { var text = @" public class A { private class Nested { } } public class B : A { void Test() { Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodAccessSyntax = (MemberAccessExpressionSyntax)callSyntax.Expression; var nestedTypeAccessSyntax = methodAccessSyntax.Expression; var typeInfo = model.GetSymbolInfo(nestedTypeAccessSyntax); Assert.Equal(CandidateReason.Inaccessible, typeInfo.CandidateReason); Assert.Equal(classNested, typeInfo.CandidateSymbols.Single()); var methodInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals), methodInfo.Symbol); compilation.VerifyDiagnostics( // (13,9): error CS0122: 'A.Nested' is inaccessible due to its protection level // Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols1() { var text = @" class C { public override int GetHashCode() { return 0; } } struct S { public override int GetHashCode() { return 0; } } class Test { int M(C c) { return c.GetHashCode } int M(S s) { return s.GetHashCode } } "; var compilation = CreateCompilation(text); var global = compilation.GlobalNamespace; var classType = global.GetMember<NamedTypeSymbol>("C"); var structType = global.GetMember<NamedTypeSymbol>("S"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccesses = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, memberAccesses.Length); var classMemberAccess = memberAccesses[0]; var structMemberAccess = memberAccesses[1]; var classInfo = model.GetSymbolInfo(classMemberAccess); var structInfo = model.GetSymbolInfo(structMemberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, classInfo.CandidateReason); Assert.Equal("System.Int32 C.GetHashCode()", classInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, structInfo.CandidateReason); Assert.Equal("System.Int32 S.GetHashCode()", structInfo.CandidateSymbols.Single().ToTestDisplayString()); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols2() { var text = @" class A { public virtual void M() { } } class B : A { public override void M() { } } class C : B { public override void M() { } } class Program { static void Main(string[] args) { C c = new C(); c.M } } "; var compilation = CreateCompilation(text); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal("void C.M()", info.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T>(T t, C c) where T : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter2() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T, U>(T t, C c) where T : U where U : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(652583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652583")] public void ParameterDefaultValueWithoutParameter() { var source = @" class A { protected void Goo(bool b, = true "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var trueLiteral = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.TrueLiteralExpression, trueLiteral.Kind()); model.GetSymbolInfo(trueLiteral); var parameterSyntax = trueLiteral.FirstAncestorOrSelf<ParameterSyntax>(); Assert.Equal(SyntaxKind.Parameter, parameterSyntax.Kind()); model.GetDeclaredSymbol(parameterSyntax); } [Fact] [WorkItem(530791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530791")] public void Repro530791() { var source = @" class Program { static void Main(string[] args) { Test test = new Test(() => { return null; }); } } class Test { } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(lambdaSyntax); var lambda = (IMethodSymbol)symbolInfo.Symbol; Assert.False(lambda.ReturnsVoid); Assert.Equal(SymbolKind.ErrorType, lambda.ReturnType.Kind); } [Fact] public void InvocationInLocalDeclarationInLambdaInConstructorInitializer() { var source = @" using System; public class C { public int M() { return null; } } public class Test { public Test() : this(c => { int i = c.M(); return i; }) { } public Test(Func<C, int> f) { } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(syntax); var methodSymbol = (IMethodSymbol)symbolInfo.Symbol; Assert.False(methodSymbol.ReturnsVoid); } [Fact] [WorkItem(654753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/654753")] public void Repro654753() { var source = @" using System; using System.Collections.Generic; using System.Linq; public class C { private readonly C Instance = new C(); bool M(IDisposable d) { using(d) { bool any = this.Instance.GetList().OfType<D>().Any(); return any; } } IEnumerable<C> GetList() { return null; } } public class D : C { } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("this", StringComparison.Ordinal); var statement = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var newSyntax = SyntaxFactory.ParseExpression("Instance.GetList().OfType<D>().Any()"); var newStatement = statement.ReplaceNode(statement.Declaration.Variables[0].Initializer.Value, newSyntax); newSyntax = newStatement.Declaration.Variables[0].Initializer.Value; SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(position, newStatement, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var newSyntaxMemberAccess = newSyntax.DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>(). Single(e => e.ToString() == "Instance.GetList().OfType<D>"); speculativeModel.GetTypeInfo(newSyntaxMemberAccess); } [Fact] [WorkItem(750557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750557")] public void MethodGroupFromMetadata() { var source = @" class Goo { delegate int D(int i); void M() { var v = ((D)(x => x)).Equals is bool; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("Equals", StringComparison.Ordinal); var equalsToken = tree.GetRoot().FindToken(position); var equalsNode = equalsToken.Parent; var symbolInfo = model.GetSymbolInfo(equalsNode); //note that we don't guarantee what symbol will come back on a method group in an is expression. Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.Length > 0); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForDefinedSymbol() { string sourceCode = @" #define X #if X //bind #define Z #endif #if Z //bind #endif // broken code cases #define A #if A + 1 //bind #endif #define B = 0 #if B //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A + 1 //bind"); Assert.Equal("A", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.Equal("B", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); Assert.True(symbolInfo.Symbol.Equals(symbolInfo.Symbol)); Assert.False(symbolInfo.Symbol.Equals(null)); PreprocessingSymbolInfo symbolInfo2 = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.NotSame(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol.GetHashCode(), symbolInfo2.Symbol.GetHashCode()); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForUndefinedSymbol() { string sourceCode = @" #define X #undef X #if X //bind #endif #if x //bind #endif #if Y //bind #define Z #endif #if Z //bind #endif // Not in preprocessor trivia #define A public class T { public int Goo(int A) { return A; //bind } } "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "x //bind"); Assert.Equal("x", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Y //bind"); Assert.Equal("Y", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A; //bind"); Assert.Null(symbolInfo.Symbol); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304"), WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void GetPreprocessingSymbolInfoForSymbolDefinedLaterInSource() { string sourceCode = @" #if Z //bind #endif #define Z "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_01() { string sourceCode = @" #define Z #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_02() { string sourceCode = @" #if true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_03() { string sourceCode = @" #if false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_04() { string sourceCode = @" #if true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_05() { string sourceCode = @" #if false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_06() { string sourceCode = @" #if true #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_07() { string sourceCode = @" #if false #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_08() { string sourceCode = @" #if true #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_09() { string sourceCode = @" #if false #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_10() { string sourceCode = @" #if true #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_11() { string sourceCode = @" #if false #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_12() { string sourceCode = @" #if false #elif false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_13() { string sourceCode = @" #if true #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_14() { string sourceCode = @" #if true #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_15() { string sourceCode = @" #if false #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_16() { string sourceCode = @" #if false #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_17() { string sourceCode = @" #if false #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_18() { string sourceCode = @" #if false #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_19() { string sourceCode = @" #if true #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_20() { string sourceCode = @" #if true #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_21() { string sourceCode = @" #if true #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_22() { string sourceCode = @" #if false #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [WorkItem(835391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835391")] [Fact] public void ConstructedErrorTypeValidation() { var text = @"class C1 : E1 { } class C2<T> : E2<T> { }"; var compilation = (Compilation)CreateCompilation(text); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); // Non-generic type. var type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[0]); Assert.False(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Non-generic error type. type = type.BaseType; Assert.False(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Generic type. type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[1]); Assert.True(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type // Generic error type. type = type.BaseType.ConstructedFrom; Assert.True(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type } [Fact] [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] public void NestedLambdaErrorRecovery() { var source = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main() { Task<IEnumerable<Task<A>>> teta = null; teta.ContinueWith(tasks => { var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. list.ToString(); }); } static B X(int x) { return null; } class A { } class B { } } "; for (int i = 0; i < 10; i++) // Ten runs to ensure consistency. { var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (13,51): error CS1503: Argument 1: cannot convert from 'Program.A' to 'int' // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_BadArgType, "t.Result").WithArguments("1", "Program.A", "int").WithLocation(13, 51), // (13,30): error CS1061: 'System.Threading.Tasks.Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?) // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Result").WithArguments("System.Threading.Tasks.Task", "Result").WithLocation(13, 30)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var invocationInfo = model.GetSymbolInfo(invocationSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, invocationInfo.CandidateReason); Assert.Null(invocationInfo.Symbol); Assert.NotEqual(0, invocationInfo.CandidateSymbols.Length); var parameterSyntax = invocationSyntax.DescendantNodes().OfType<ParameterSyntax>().First(); var parameterSymbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal("System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<Program.A>>>", parameterSymbol.Type.ToTestDisplayString()); } } [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [WorkItem(854548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854548")] [Fact] public void SemanticModelLambdaErrorRecovery() { var source = @" using System; class Program { static void Main() { M(() => 1); // Neither overload wins. } static void M(Func<string> a) { } static void M(Func<char> a) { } } "; { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); } { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversion = model.ClassifyConversion(lambdaSyntax, otherFuncType); CheckIsAssignableTo(model, lambdaSyntax); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); // Not affected by call to ClassifyConversion. } } [Fact] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] public void ClassifyConversionOnNull() { var source = @" class Program { static void Main() { M(null); // Ambiguous. } static void M(A a) { } static void M(B b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var nullSyntax = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var conversion = model.ClassifyConversion(nullSyntax, typeC); CheckIsAssignableTo(model, nullSyntax); Assert.Equal(ConversionKind.ImplicitReference, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnLambda() { var source = @" using System; class Program { static void Main() { M(() => null); } static void M(Func<A> a) { } } class A { } class B { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeB = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("B"); var typeFuncB = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeB); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncB); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousLambda() { var source = @" using System; class Program { static void Main() { M(() => null); // Ambiguous. } static void M(Func<A> a) { } static void M(Func<B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(System.Func<A>)' and 'Program.M(System.Func<B>)' // M(() => null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(System.Func<A>)", "Program.M(System.Func<B>)").WithLocation(8, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var typeFuncC = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeC); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncC); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousMethodGroup() { var source = @" using System; class Base<T> { public A N(T t) { throw null; } public B N(int t) { throw null; } } class Derived : Base<int> { void Test() { M(N); // Ambiguous. } static void M(Func<int, A> a) { } static void M(Func<int, B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Derived.M(System.Func<int, A>)' and 'Derived.M(System.Func<int, B>)' // M(N); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Derived.M(System.Func<int, A>)", "Derived.M(System.Func<int, B>)").WithLocation(14, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var methodGroupSyntax = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>().Single().Expression; var global = comp.GlobalNamespace; var typeA = global.GetMember<INamedTypeSymbol>("A"); var typeB = global.GetMember<INamedTypeSymbol>("B"); var typeC = global.GetMember<INamedTypeSymbol>("C"); var typeInt = comp.GetSpecialType(SpecialType.System_Int32); var typeFunc = comp.GetWellKnownType(WellKnownType.System_Func_T2); var typeFuncA = typeFunc.Construct(typeInt, typeA); var typeFuncB = typeFunc.Construct(typeInt, typeB); var typeFuncC = typeFunc.Construct(typeInt, typeC); var conversionA = model.ClassifyConversion(methodGroupSyntax, typeFuncA); CheckIsAssignableTo(model, methodGroupSyntax); Assert.Equal(ConversionKind.MethodGroup, conversionA.Kind); var conversionB = model.ClassifyConversion(methodGroupSyntax, typeFuncB); Assert.Equal(ConversionKind.MethodGroup, conversionB.Kind); var conversionC = model.ClassifyConversion(methodGroupSyntax, typeFuncC); Assert.Equal(ConversionKind.NoConversion, conversionC.Kind); } [WorkItem(872064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872064")] [Fact] public void PartialMethodImplementationDiagnostics() { var file1 = @" namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m); } } "; var file2 = @" namespace ConsoleApplication1 { partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m) { c = new MyUndefinedMethod(23, true); } } } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var comp = CreateCompilation(new[] { tree1, tree2 }); var model = comp.GetSemanticModel(tree2); var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(2, errs.Count()); } [Fact] public void PartialTypeDiagnostics_StaticConstructors() { var file1 = @" partial class C { static C() {} } "; var file2 = @" partial class C { static C() {} } "; var file3 = @" partial class C { static C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); model3.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").StaticConstructors.Length); } [Fact] public void PartialTypeDiagnostics_Constructors() { var file1 = @" partial class C { C() {} } "; var file2 = @" partial class C { C() {} } "; var file3 = @" partial class C { C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); model3.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Length); } [WorkItem(1076661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1076661")] [Fact] public void Bug1076661() { const string source = @" using X = System.Collections.Generic.List<dynamic>; class Test { void Goo(ref X. x) { } }"; var comp = CreateCompilation(source); var diag = comp.GetDiagnostics(); } [Fact] public void QueryClauseInBadStatement_Catch() { var source = @"using System; class C { static void F(object[] c) { catch (Exception) when (from o in c where true) { } } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(); var expr = tokens.Single(t => t.Kind() == SyntaxKind.TrueKeyword).Parent; Assert.Null(model.GetSymbolInfo(expr).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(expr).Type.SpecialType); } [Fact] public void GetSpecialType_ThrowsOnLessThanZero() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = (SpecialType)(-1); var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] public void GetSpecialType_ThrowsOnGreaterThanCount() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = SpecialType.Count + 1; var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] [WorkItem(34984, "https://github.com/dotnet/roslyn/issues/34984")] public void ConversionIsExplicit_UnsetConversionKind() { var source = @"class C1 { } class C2 { public void M() { var c = new C1(); foreach (string item in c.Items) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var foreachSyntaxNode = root.DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var foreachSymbolInfo = model.GetForEachStatementInfo(foreachSyntaxNode); Assert.Equal(Conversion.UnsetConversion, foreachSymbolInfo.CurrentConversion); Assert.True(foreachSymbolInfo.CurrentConversion.Exists); Assert.False(foreachSymbolInfo.CurrentConversion.IsImplicit); } [Fact, WorkItem(29933, "https://github.com/dotnet/roslyn/issues/29933")] public void SpeculativelyBindBaseInXmlDoc() { var text = @" class C { /// <summary> </summary> static void M() { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf(">", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression("base"); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); } [Fact] [WorkItem(42840, "https://github.com/dotnet/roslyn/issues/42840")] public void DuplicateTypeArgument() { var source = @"class A<T> { } class B<T, U, U> where T : A<U> where U : class { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,15): error CS0692: Duplicate type parameter 'U' // class B<T, U, U> Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 15), // (5,17): error CS0229: Ambiguity between 'U' and 'U' // where T : A<U> Diagnostic(ErrorCode.ERR_AmbigMember, "U").WithArguments("U", "U").WithLocation(5, 17)); comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var typeParameters = tree.GetRoot().DescendantNodes().OfType<TypeParameterSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 1]); Assert.False(symbol.IsReferenceType); symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 2]); Assert.True(symbol.IsReferenceType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class GetSemanticInfoTests : SemanticModelTestBase { [WorkItem(544320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544320")] [Fact] public void TestBug12592() { var text = @" class B { public B(int x = 42) {} } class D : B { public D(int y) : base(/*<bind>*/x/*</bind>*/: y) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Parameter, sym.Symbol.Kind); Assert.Equal("x", sym.Symbol.Name); } [WorkItem(541948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541948")] [Fact] public void DelegateArgumentType() { var text = @"using System; delegate void MyEvent(); class Test { event MyEvent Clicked; void Handler() { } public void Run() { Test t = new Test(); t.Clicked += new MyEvent(/*<bind>*/Handler/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [WorkItem(541949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541949")] [Fact] public void LambdaWithParenthesis_BindOutsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = /*<bind>*/( delegate() { return 0; } )/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact] public void LambdaWithParenthesis_BindInsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = (/*<bind>*/ delegate() { return 0; }/*</bind>*/) ; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [Fact, WorkItem(528656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528656")] public void SemanticInfoForInvalidExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/ delegate * delegate /*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Null(sym.Symbol); } [WorkItem(541973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541973")] [Fact] public void LambdaAsAttributeArgumentErr() { var text = @"using System; delegate void D(); class MyAttr: Attribute { public MyAttr(D d) { } } [MyAttr((D)/*<bind>*/delegate { }/*</bind>*/)] // CS0182 public class A { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ClassifyConversionImplicit() { var text = @"using System; enum E { One, Two, Three } public class Test { static byte[] ary; static int Main() { // Identity ary = new byte[3]; // ImplicitConstant ary[0] = 0x0F; // ImplicitNumeric ushort ret = ary[0]; // ImplicitReference Test obj = null; // Identity obj = new Test(); // ImplicitNumeric obj.M(ary[0]); // boxing object box = -1; // ImplicitEnumeration E e = 0; // Identity E e2 = E.Two; // bind 'Two' return (int)ret; } void M(ulong p) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[1] as TypeDeclarationSyntax; Assert.Equal(3, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(10, mainStats.Count); // ary = new byte[3]; var v1 = (mainStats[0] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v1.Kind()); ConversionTestHelper(model, (v1 as AssignmentExpressionSyntax).Right, ConversionKind.Identity, ConversionKind.Identity); // ary[0] = 0x0F; var v2 = (mainStats[1] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitConstant, ConversionKind.ExplicitNumeric); // ushort ret = ary[0]; var v3 = (mainStats[2] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v3[0].Initializer.Value, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object obj01 = null; var v4 = (mainStats[3] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitReference, ConversionKind.NoConversion); // obj.M(ary[0]); var v6 = (mainStats[5] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.InvocationExpression, v6.Kind()); var v61 = (v6 as InvocationExpressionSyntax).ArgumentList.Arguments; ConversionTestHelper(model, v61[0].Expression, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object box = -1; var v7 = (mainStats[6] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v7[0].Initializer.Value, ConversionKind.Boxing, ConversionKind.Boxing); // E e = 0; var v8 = (mainStats[7] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v8[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E e2 = E.Two; var v9 = (mainStats[8] as LocalDeclarationStatementSyntax).Declaration.Variables; var v9val = (MemberAccessExpressionSyntax)(v9[0].Initializer.Value); var v9right = v9val.Name; ConversionTestHelper(model, v9right, ConversionKind.Identity, ConversionKind.Identity); } private void TestClassifyConversionBuiltInNumeric(string from, string to, ConversionKind ck) { const string template = @" class C {{ static void Goo({1} v) {{ }} static void Main() {{ {0} v = default({0}); Goo({2}v); }} }} "; var isExplicitConversion = ck == ConversionKind.ExplicitNumeric; var source = string.Format(template, from, to, isExplicitConversion ? "(" + to + ")" : ""); var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var c = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; var main = (MethodDeclarationSyntax)c.Members[1]; var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)main.Body.Statements[1]).Expression; var arg = call.ArgumentList.Arguments[0].Expression; if (isExplicitConversion) { ConversionTestHelper(model, ((CastExpressionSyntax)arg).Expression, model.GetTypeInfo(arg).ConvertedType, ck); } else { ConversionTestHelper(model, arg, ck, ck); } } [Fact] public void ClassifyConversionBuiltInNumeric() { const ConversionKind ID = ConversionKind.Identity; const ConversionKind IN = ConversionKind.ImplicitNumeric; const ConversionKind XN = ConversionKind.ExplicitNumeric; var types = new[] { "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char", "float", "double", "decimal" }; var conversions = new ConversionKind[,] { // to sb b s us i ui l ul c f d m // from /* sb */ { ID, XN, IN, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* b */ { XN, ID, IN, IN, IN, IN, IN, IN, XN, IN, IN, IN }, /* s */ { XN, XN, ID, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* us */ { XN, XN, XN, ID, IN, IN, IN, IN, XN, IN, IN, IN }, /* i */ { XN, XN, XN, XN, ID, XN, IN, XN, XN, IN, IN, IN }, /* ui */ { XN, XN, XN, XN, XN, ID, IN, IN, XN, IN, IN, IN }, /* l */ { XN, XN, XN, XN, XN, XN, ID, XN, XN, IN, IN, IN }, /* ul */ { XN, XN, XN, XN, XN, XN, XN, ID, XN, IN, IN, IN }, /* c */ { XN, XN, XN, IN, IN, IN, IN, IN, ID, IN, IN, IN }, /* f */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, IN, XN }, /* d */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, XN }, /* m */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID } }; for (var from = 0; from < types.Length; from++) { for (var to = 0; to < types.Length; to++) { TestClassifyConversionBuiltInNumeric(types[from], types[to], conversions[from, to]); } } } [WorkItem(527486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527486")] [Fact] public void ClassifyConversionExplicit() { var text = @"using System; public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // Cast y = (uint) x; // Boxing obj01 = x; // Cast x = (int)obj01; // NoConversion obj02 = (Test)obj01; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = (uint) x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v1 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_UInt32), ConversionKind.ExplicitNumeric); // obj01 = x; var v2 = (mainStats[2] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, comp.GetSpecialType(SpecialType.System_Object), ConversionKind.Boxing); // x = (int)obj01; var v3 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v3 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_Int32), ConversionKind.Unboxing); // obj02 = (Test)obj01; var tsym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault(); var v4 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v4 as CastExpressionSyntax).Expression, tsym, ConversionKind.ExplicitReference); } [Fact] public void DiagnosticsInStages() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { // ExplicitReference -> CS0266 obj02 = obj01; } binding error; parse err } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(4, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(2, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(1, errs.Count()); } [Fact] public void DiagnosticsFilteredWithPragmas() { var text = @" public class Test { #pragma warning disable 1633 #pragma xyzzy whatever #pragma warning restore 1633 } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); } [Fact] public void ClassifyConversionExplicitNeg() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // ExplicitNumeric - CS0266 y = x; // Boxing obj01 = x; // unboxing - CS0266 x = obj01; // ExplicitReference -> CS0266 obj02 = obj01; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v1, ConversionKind.ExplicitNumeric, ConversionKind.ExplicitNumeric); // x = obj01; var v2 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v2, ConversionKind.Unboxing, ConversionKind.Unboxing); // obj02 = obj01; var v3 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v3, ConversionKind.ExplicitReference, ConversionKind.ExplicitReference); // CC var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(0, errs.Count()); } [WorkItem(527767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527767")] [Fact] public void ClassifyConversionNullable() { var text = @"using System; public class Test { static void Main() { // NullLiteral sbyte? nullable = null; // ImplicitNullable uint? nullable01 = 100; ushort localVal = 123; // ImplicitNullable nullable01 = localVal; E e = 0; E? en = 0; // Oddly enough, C# classifies this as an implicit enumeration conversion. } } enum E { zero, one } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(1, testClass.Members.Count); var mainMethod = testClass.Members[0] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(6, mainStats.Count); // sbyte? nullable = null; var v1 = (mainStats[0] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v1[0].Initializer.Value, ConversionKind.NullLiteral, ConversionKind.NoConversion); // uint? nullable01 = 100; var v2 = (mainStats[1] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v2[0].Initializer.Value, ConversionKind.ImplicitNullable, ConversionKind.ExplicitNullable); // nullable01 = localVal; var v3 = (mainStats[3] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v3.Kind()); ConversionTestHelper(model, (v3 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitNullable, ConversionKind.ImplicitNullable); // E e = 0; var v4 = (mainStats[4] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E? en = 0; var v5 = (mainStats[5] as LocalDeclarationStatementSyntax).Declaration.Variables; // Bug#5035 (ByDesign): Conversion from literal 0 to nullable enum is Implicit Enumeration (not ImplicitNullable). Conversion from int to nullable enum is Explicit Nullable. ConversionTestHelper(model, v5[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitNullable); } [Fact, WorkItem(543994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543994")] public void ClassifyConversionImplicitUserDef() { var text = @"using System; class MyClass { public static bool operator true(MyClass p) { return true; } public static bool operator false(MyClass p) { return false; } public static MyClass operator &(MyClass mc1, MyClass mc2) { return new MyClass(); } public static int Main() { var cls1 = new MyClass(); var cls2 = new MyClass(); if (/*<bind0>*/cls1/*</bind0>*/) return 0; if (/*<bind1>*/cls1 && cls2/*</bind1>*/) return 1; return 2; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var expr2 = exprs.Last(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // It was ImplicitUserDef -> Design Meeting resolution: not expose op_True|False as conversion through API var impconv = model.GetConversion(expr1); Assert.Equal(Conversion.Identity, impconv); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.Equal("Identity", conv.ToString()); conv = model.ClassifyConversion(expr2, info.ConvertedType); CheckIsAssignableTo(model, expr2); Assert.Equal(impconv, conv); } [Fact, WorkItem(1019372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019372")] public void ClassifyConversionImplicitUserDef02() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { int? i = /*<bind0>*/this/*</bind0>*/; } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var impconv = model.GetConversion(expr1); Assert.True(impconv.IsImplicit); Assert.True(impconv.IsUserDefined); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.True(conv.IsImplicit); Assert.True(conv.IsUserDefined); } private void CheckIsAssignableTo(SemanticModel model, ExpressionSyntax syntax) { var info = model.GetTypeInfo(syntax); var conversion = info.Type != null && info.ConvertedType != null ? model.Compilation.ClassifyConversion(info.Type, info.ConvertedType) : Conversion.NoConversion; Assert.Equal(conversion.IsImplicit, model.Compilation.HasImplicitConversion(info.Type, info.ConvertedType)); } [Fact, WorkItem(544151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544151")] public void PublicViewOfPointerConversions() { ValidateConversion(Conversion.PointerToVoid, ConversionKind.ImplicitPointerToVoid); ValidateConversion(Conversion.NullToPointer, ConversionKind.ImplicitNullToPointer); ValidateConversion(Conversion.PointerToPointer, ConversionKind.ExplicitPointerToPointer); ValidateConversion(Conversion.IntegerToPointer, ConversionKind.ExplicitIntegerToPointer); ValidateConversion(Conversion.PointerToInteger, ConversionKind.ExplicitPointerToInteger); ValidateConversion(Conversion.IntPtr, ConversionKind.IntPtr); } #region "Conversion helper" private void ValidateConversion(Conversion conv, ConversionKind kind) { Assert.Equal(conv.Kind, kind); switch (kind) { case ConversionKind.NoConversion: Assert.False(conv.Exists); Assert.False(conv.IsImplicit); Assert.False(conv.IsExplicit); break; case ConversionKind.Identity: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsIdentity); break; case ConversionKind.ImplicitNumeric: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ImplicitEnumeration: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ImplicitNullable: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.NullLiteral: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullLiteral); break; case ConversionKind.ImplicitReference: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Boxing: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsBoxing); break; case ConversionKind.ImplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ExplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsExplicit); Assert.False(conv.IsImplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ImplicitConstant: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsConstantExpression); break; case ConversionKind.ImplicitUserDefined: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.AnonymousFunction: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsAnonymousFunction); break; case ConversionKind.MethodGroup: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsMethodGroup); break; case ConversionKind.ExplicitNumeric: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ExplicitEnumeration: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ExplicitNullable: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.ExplicitReference: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Unboxing: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUnboxing); break; case ConversionKind.ExplicitUserDefined: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.ImplicitNullToPointer: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ImplicitPointerToVoid: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitIntegerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToInteger: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.IntPtr: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.False(conv.IsPointer); Assert.True(conv.IsIntPtr); break; } } /// <summary> /// /// </summary> /// <param name="semanticModel"></param> /// <param name="expr"></param> /// <param name="ept1">expr -> TypeInParent</param> /// <param name="ept2">Type(expr) -> TypeInParent</param> private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ConversionKind ept1, ConversionKind ept2) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var conv = semanticModel.GetConversion(expr); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, info.ConvertedType); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(ept1, act1.Kind); ValidateConversion(act1, ept1); ValidateConversion(act1, conv.Kind); if (ept2 == ConversionKind.NoConversion) { Assert.Null(info.Type); } else { Assert.NotNull(info.Type); var act2 = semanticModel.Compilation.ClassifyConversion(info.Type, info.ConvertedType); Assert.Equal(ept2, act2.Kind); ValidateConversion(act2, ept2); } } private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ITypeSymbol expsym, ConversionKind expkind) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, expsym); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(expkind, act1.Kind); ValidateConversion(act1, expkind); } #endregion [Fact] public void EnumOffsets() { // sbyte EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 1))); EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 2))); EnumOffset(ConstantValue.Create((sbyte)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(-1))); EnumOffset(ConstantValue.Create((sbyte)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(1))); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)sbyte.MaxValue)); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // byte EnumOffset(ConstantValue.Create((byte)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)1)); EnumOffset(ConstantValue.Create((byte)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)2)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)byte.MaxValue)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // short EnumOffset(ConstantValue.Create((short)short.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 1))); EnumOffset(ConstantValue.Create((short)short.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 2))); EnumOffset(ConstantValue.Create((short)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(-1))); EnumOffset(ConstantValue.Create((short)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(1))); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)short.MaxValue)); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ushort EnumOffset(ConstantValue.Create((ushort)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)1)); EnumOffset(ConstantValue.Create((ushort)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)2)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)ushort.MaxValue)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // int EnumOffset(ConstantValue.Create((int)int.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 1))); EnumOffset(ConstantValue.Create((int)int.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 2))); EnumOffset(ConstantValue.Create((int)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(-1))); EnumOffset(ConstantValue.Create((int)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(1))); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)int.MaxValue)); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // uint EnumOffset(ConstantValue.Create((uint)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)1)); EnumOffset(ConstantValue.Create((uint)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)2)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)uint.MaxValue)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // long EnumOffset(ConstantValue.Create((long)long.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 1))); EnumOffset(ConstantValue.Create((long)long.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 2))); EnumOffset(ConstantValue.Create((long)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(-1))); EnumOffset(ConstantValue.Create((long)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(1))); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)long.MaxValue)); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ulong EnumOffset(ConstantValue.Create((ulong)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)1)); EnumOffset(ConstantValue.Create((ulong)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)2)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)ulong.MaxValue)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); } private void EnumOffset(ConstantValue constantValue, uint offset, EnumOverflowKind expectedOverflowKind, ConstantValue expectedValue) { ConstantValue actualValue; var actualOverflowKind = EnumConstantHelper.OffsetValue(constantValue, offset, out actualValue); Assert.Equal(expectedOverflowKind, actualOverflowKind); Assert.Equal(expectedValue, actualValue); } [Fact] public void TestGetSemanticInfoInParentInIf() { var compilation = CreateCompilation(@" class C { void M(int x) { if (x == 10) {} } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var ifStatement = (IfStatementSyntax)methodDecl.Body.Statements[0]; var condition = ifStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.Type.Name); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [Fact] public void TestGetSemanticInfoInParentInFor() { var compilation = CreateCompilation(@" class C { void M(int x) { for (int i = 0; i < 10; i = i + 1) { } } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var forStatement = (ForStatementSyntax)methodDecl.Body.Statements[0]; var condition = forStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.ConvertedType.Name); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")] [Fact] public void NoMembersForVoidReturnType() { var text = @" class C { void M() { /*<bind>*/System.Console.WriteLine()/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); IMethodSymbol methodSymbol = (IMethodSymbol)bindInfo.Symbol; ITypeSymbol returnType = methodSymbol.ReturnType; var symbols = model.LookupSymbols(0, returnType); Assert.Equal(0, symbols.Length); } [WorkItem(540767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540767")] [Fact] public void BindIncompleteVarDeclWithDoKeyword() { var code = @" class Test { static int Main(string[] args) { do"; var compilation = CreateCompilation(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxList = GetExprSyntaxList(tree); Assert.Equal(6, exprSyntaxList.Count); // Note the omitted array size expression in "string[]" Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[4].Kind()); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[5].Kind()); Assert.Equal("", exprSyntaxList[4].ToFullString()); Assert.Equal("", exprSyntaxList[5].ToFullString()); var exprSyntaxToBind = exprSyntaxList[exprSyntaxList.Count - 2]; model.GetSemanticInfoSummary(exprSyntaxToBind); } [Fact] public void TestBindBaseConstructorInitializer() { var text = @" class C { C() : base() { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("System.Object..ctor()", baseConstructor.ToTestDisplayString()); } [Fact] public void TestBindThisConstructorInitializer() { var text = @" class C { C() : this(1) { } C(int x) { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("C..ctor(System.Int32 x)", baseConstructor.ToTestDisplayString()); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void BindThisStaticConstructorInitializer() { var text = @" class MyClass { static MyClass() : this() { intI = 2; } public MyClass() { } static int intI = 1; } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var invokedConstructor = (IMethodSymbol)bindInfo.Symbol; Assert.Equal(MethodKind.Constructor, invokedConstructor.MethodKind); Assert.Equal("MyClass..ctor()", invokedConstructor.ToTestDisplayString()); } [WorkItem(541053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541053")] [Fact] public void CheckAndAdjustPositionOutOfRange() { var text = @" using System; > 1 "; var tree = Parse(text, options: TestOptions.Script); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); Assert.NotEqual(0, root.SpanStart); var stmt = (GlobalStatementSyntax)root.Members.Single(); var expr = ((ExpressionStatementSyntax)stmt.Statement).Expression; Assert.Equal(SyntaxKind.GreaterThanExpression, expr.Kind()); var info = model.GetSemanticInfoSummary(expr); Assert.Equal(SpecialType.System_Boolean, info.Type.SpecialType); } [Fact] public void AddAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += /*<bind>*/value/*</bind>*/; } remove { e -= value; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventAdd, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void RemoveAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += value; } remove { e -= /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventRemove, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void FieldLikeEventInitializer() { var text = @" class C { event System.Action E = /*<bind>*/new System.Action(() => { })/*</bind>*/; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); } [Fact] public void FieldLikeEventInitializer2() { var text = @" class C { event System.Action E = new /*<bind>*/System.Action/*</bind>*/(() => { }); } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Null(bindInfo.Type); Assert.Equal(systemActionType, bindInfo.Symbol); } [Fact] public void CustomEventAccess() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void FieldLikeEventAccess() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void CustomEventAssignmentOperator() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void FieldLikeEventAssignmentOperator() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void CustomEventMissingAssignmentOperator() { var text = @" class C { event System.Action E { /*add { }*/ remove { } } //missing add void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); } private static INamedTypeSymbol GetSystemActionType(CSharpCompilation comp) { return GetSystemActionType((Compilation)comp); } private static INamedTypeSymbol GetSystemActionType(Compilation comp) { return (INamedTypeSymbol)comp.GlobalNamespace.GetMember<INamespaceSymbol>("System").GetMembers("Action").Where(s => !((INamedTypeSymbol)s).IsGenericType).Single(); } [Fact] public void IndexerAccess() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); Assert.Equal(indexerSymbol, bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessOverloadResolutionFailure() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol1 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); var indexerSymbol2 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 2).Single().GetPublicSymbol(); var candidateIndexers = ImmutableArray.Create<ISymbol>(indexerSymbol1, indexerSymbol2); Assert.Null(bindInfo.Symbol); Assert.True(bindInfo.CandidateSymbols.SetEquals(candidateIndexers, EqualityComparer<ISymbol>.Default)); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); //still have the type since all candidates agree Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessNoIndexers() { var text = @" class C { void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(TypeKind.Error, bindInfo.Type.TypeKind); Assert.Equal(TypeKind.Struct, bindInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess1() { var text = @" public class Test { public int Fld; public int Func() { return (int)(/*<bind>*/Fld<int>/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, bindInfo.CandidateReason); Assert.Equal(1, bindInfo.CandidateSymbols.Length); var candidate = bindInfo.CandidateSymbols.Single(); Assert.Equal(SymbolKind.Field, candidate.Kind); Assert.Equal("Fld", candidate.Name); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess2() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld</*<bind>*/Test/*</bind>*/>); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal("Test", symbol.Name); } [WorkItem(528785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528785")] [Fact] public void TopLevelIndexer() { var text = @" this[double E] { get { return /*<bind>*/E/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); } [WorkItem(542360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542360")] [Fact] public void TypeAndMethodHaveSameTypeParameterName() { var text = @" interface I<T> { void Goo<T>(); } class A<T> : I<T> { void I</*<bind>*/T/*</bind>*/>.Goo<T>() { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("T", symbol.Name); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("A"), symbol.ContainingSymbol); //from the type, not the method } [WorkItem(542436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542436")] [Fact] public void RecoveryFromBadNamespaceDeclaration() { var text = @"namespace alias:: using alias = /*<bind>*/N/*</bind>*/; namespace N { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); } /// Test that binding a local declared with var binds the same way when localSymbol.Type is called before BindVariableDeclaration. /// Assert occurs if the two do not compute the same type. [Fact] [WorkItem(542634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542634")] public void VarInitializedWithStaticType() { var text = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static string xunit = " + "@" + @"..\..\Closed\Tools\xUnit\xunit.console.x86.exe" + @"; static string test = " + @"Roslyn.VisualStudio.Services.UnitTests.dll" + @"; static string commandLine = test" + @" /html log.html" + @"; static void Main(string[] args) { var options = CreateOptions(); /*<bind>*/Parallel/*</bind>*/.For(0, 100, RunTest, options); } private static Parallel CreateOptions() { var result = new ParallelOptions(); } private static void RunTest(int i) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); // Bind Parallel from line Parallel.For(0, 100, RunTest, options); // This will implicitly bind "var" to determine type of options. // This calls LocalSymbol.GetType var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var varIdentifier = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().DescendantNodes().First(n => n.ToString() == "var"); // var from line var options = CreateOptions; // Explicitly bind "var". // This path calls BindvariableDeclaration. bindInfo = model.GetSemanticInfoSummary(varIdentifier); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerParameter() { var text = @" class C { int this[int x] { get { return /*<bind>*/x/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "x"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerValueParameter() { var text = @" class C { int this[int x] { set { x = /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("value", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "value"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542777")] [Fact] public void IndexerThisParameter() { var text = @" class C { int this[int x] { set { System.Console.Write(/*<bind>*/this/*</bind>*/); } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ThisExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("this", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); } [WorkItem(542592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542592")] [Fact] public void TypeParameterParamsParameter() { var text = @" class Test<T> { public void Method(params T arr) { } } class Program { static void Main(string[] args) { new Test<int[]>()./*<bind>*/Method/*</bind>*/(new int[][] { }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); var candidate = (IMethodSymbol)bindInfo.CandidateSymbols.Single(); Assert.Equal("void Test<System.Int32[]>.Method(params System.Int32[] arr)", candidate.ToTestDisplayString()); Assert.Equal(TypeKind.Array, candidate.Parameters.Last().Type.TypeKind); Assert.Equal(TypeKind.TypeParameter, ((IMethodSymbol)candidate.OriginalDefinition).Parameters.Last().Type.TypeKind); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void ParameterDefaultValues() { var text = @" struct S { void M( int i = 1, string str = ""hello"", object o = null, S s = default(S)) { /*<bind>*/M/*</bind>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var method = (IMethodSymbol)bindInfo.Symbol; Assert.NotNull(method); var parameters = method.Parameters; Assert.Equal(4, parameters.Length); Assert.True(parameters[0].HasExplicitDefaultValue); Assert.Equal(1, parameters[0].ExplicitDefaultValue); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal("hello", parameters[1].ExplicitDefaultValue); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultValue); Assert.True(parameters[3].HasExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultValue); } [WorkItem(542764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542764")] [Fact] public void UnboundGenericTypeArity() { var text = @" class C<T, U, V> { void M() { System.Console.Write(typeof(/*<bind>*/C<,,>/*</bind>*/)); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var nameSyntaxToBind = (SimpleNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, nameSyntaxToBind.Kind()); Assert.Equal(3, nameSyntaxToBind.Arity); var bindInfo = model.GetSymbolInfo(nameSyntaxToBind); var type = (INamedTypeSymbol)bindInfo.Symbol; Assert.NotNull(type); Assert.True(type.IsUnboundGenericType); Assert.Equal(3, type.Arity); Assert.Equal("C<,,>", type.ToTestDisplayString()); } [Fact] public void GetType_VoidArray() { var text = @" class C { void M() { var x = typeof(/*<bind>*/System.Void[]/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ArrayType, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var arrayType = (IArrayTypeSymbol)bindInfo.Symbol; Assert.NotNull(arrayType); Assert.Equal("System.Void[]", arrayType.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance1() { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public class C<T> where T : IA, IB // can find IA.P in two different ways { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance2() //add hiding member in derived interface { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IA, IB { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance3() //reverse order of interface list (shouldn't matter) { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IB, IA { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance4() //Two interfaces with a common base { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public interface IC : IA { } public class C<T> where T : IB, IC { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup1() { var types = @" public interface IA { object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA", "P", out _); Assert.Equal("System.Object IA.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup2() { var types = @" public interface IA { object P { get; } } public interface IB { object P { get; } } "; ITypeParameterSymbol typeParameter; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out typeParameter); Assert.True(members.SetEquals(typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics().Select(i => i.GetMember<IPropertySymbol>("P")))); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup3() { var types = @" public interface IA { object P { get; } } public interface IB : IA { new object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out _); Assert.Equal("System.Object IB.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup4() { var types = @" public interface IA { object P { get; } } public class D { public object P { get; set; } } "; var members = LookupTypeParameterMembers(types, "D, IA", "P", out _); Assert.Equal("System.Object D.P { get; set; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup5() { var types = @" public interface IA { void M(); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.Equal("void IA.M()", members.Single().ToTestDisplayString()); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void D.M()" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup6() { var types = @" public interface IA { void M(); void M(int x); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void IA.M(System.Int32 x)" })); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void D.M()", "void IA.M()", "void IA.M(System.Int32 x)" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup7() { var types = @" public interface IA { string ToString(); } public class D { public new string ToString() { return null; } } "; var members = LookupTypeParameterMembers(types, "IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String IA.ToString()" })); members = LookupTypeParameterMembers(types, "D, IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String D.ToString()", "System.String IA.ToString()" })); } private IEnumerable<ISymbol> LookupTypeParameterMembers(string types, string constraints, string memberName, out ITypeParameterSymbol typeParameter) { var template = @" {0} public class C<T> where T : {1} {{ void M() {{ System.Console.WriteLine(/*<bind>*/default(T)/*</bind>*/); }} }} "; var tree = Parse(string.Format(template, types, constraints)); var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var classC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); typeParameter = classC.TypeParameters.Single(); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.DefaultExpression, exprSyntaxToBind.Kind()); return model.LookupSymbols(exprSyntaxToBind.SpanStart, typeParameter, memberName); } [WorkItem(542966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542966")] [Fact] public async Task IndexerMemberRaceAsync() { var text = @" using System; interface IA { [System.Runtime.CompilerServices.IndexerName(""Goo"")] string this[int index] { get; } } class A : IA { public virtual string this[int index] { get { return """"; } } string IA.this[int index] { get { return """"; } } } class B : A, IA { public override string this[int index] { get { return """"; } } } class Program { public static void Main(string[] args) { IA x = new B(); Console.WriteLine(x[0]); } } "; TimeSpan timeout = TimeSpan.FromSeconds(2); for (int i = 0; i < 20; i++) { var comp = CreateCompilation(text); var task1 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers()); var task2 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMembers()); if (i % 2 == 0) { task1.Start(); task2.Start(); } else { task2.Start(); task1.Start(); } comp.VerifyDiagnostics(); await Task.WhenAll(task1, task2); } } [Fact] public void ImplicitDeclarationMultipleDeclarators() { var text = @" using System.IO; class C { static void Main() { /*<bind>*/var a = new StreamWriter(""""), b = new StreamReader("""")/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (8,19): error CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/var a = new StreamWriter(""), b = new StreamReader("")/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")").WithLocation(8, 19) ); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var typeInfo = model.GetSymbolInfo(expr); // the type info uses the type inferred for the first declared local Assert.Equal("System.IO.StreamWriter", typeInfo.Symbol.ToTestDisplayString()); } [WorkItem(543169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543169")] [Fact] public void ParameterOfLambdaPassedToOutParameter() { var text = @" using System.Linq; class D { static void Main(string[] args) { string[] str = new string[] { }; label1: var s = str.Where(out /*<bind>*/x/*</bind>*/ => { return x == ""1""; }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parameterSymbol = model.GetDeclaredSymbol(lambdaSyntax.Parameter); Assert.NotNull(parameterSymbol); Assert.Equal("x", parameterSymbol.Name); Assert.Equal(MethodKind.AnonymousFunction, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")] [Fact] public void MemberAccessExpressionResults() { var text = @" class C { public static int A; public static byte B() { return 3; } public static string D { get; set; } static void Main(string[] args) { /*<bind0>*/C.A/*</bind0>*/; /*<bind1>*/C.B/*</bind1>*/(); /*<bind2>*/C.D/*</bind2>*/; /*<bind3>*/C.B()/*</bind3>*/; int goo = /*<bind4>*/C.B()/*</bind4>*/; goo = /*<bind5>*/C.B/*</bind5>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); for (int i = 0; i < exprs.Count; i++) { var expr = exprs[i]; var symbolInfo = model.GetSymbolInfo(expr); Assert.NotNull(symbolInfo.Symbol); var typeInfo = model.GetTypeInfo(expr); switch (i) { case 0: Assert.Equal("A", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; case 1: case 5: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.Null(typeInfo.Type); break; case 2: Assert.Equal("D", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()); break; case 3: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Byte", typeInfo.ConvertedType.ToTestDisplayString()); break; case 4: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; } // switch } } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForUncheckedExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/unchecked(42 + 42.1)/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Double System.Double.op_Addition(System.Double left, System.Double right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Double, info.Type.SpecialType); Assert.Equal(SpecialType.System_Double, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForCheckedExpression() { var text = @" class Program { public static int Add(int a, int b) { return /*<bind>*/checked(a+b)/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void CheckedUncheckedExpression() { var text = @" class Test { public void F() { int y = /*<bind>*/(checked(unchecked((1))))/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact] public void SymbolInfoForImplicitOperatorParameter() { var text = @" class Program { public Program(string s) { } public static implicit operator Program(string str) { return new Program(/*<bind>*/str/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetSymbolInfo(expr); var symbol = info.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)symbol.ContainingSymbol).MethodKind); } [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] [WorkItem(543560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543560")] [Fact] public void BrokenPropertyDeclaration() { var source = @" using System; Class Program // this will get a Property declaration ... *sigh* { static void Main(string[] args) { Func<int, int> f = /*<bind0>*/x/*</bind0>*/ => x + 1; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().First(); var declaredSymbol = model.GetDeclaredSymbol(expr); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedLogicalOperator() { var text = @" class C { public static C operator &(C c1, C c2) { return c1 ?? c2; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 && c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.BitwiseAndOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedUnaryOperator() { var text = @" class C { public static C operator+(C c1) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.UnaryPlusOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedExplicitConversion() { var text = @" class C { public static explicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ExplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedImplicitConversion() { var text = @" class C { public static implicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ImplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedTrueOperator() { var text = @" class C { public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c = new C(); if (/*<bind>*/c/*</bind>*/) { } } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var type = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); var symbol = symbolInfo.Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("c", symbol.Name); Assert.Equal(type, ((ILocalSymbol)symbol).Type); var typeInfo = model.GetTypeInfo(expr); Assert.Equal(type, typeInfo.Type); Assert.Equal(type, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(Conversion.Identity, conv); Assert.False(model.GetConstantValue(expr).HasValue); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedIncrement() { var text = @" class C { public static C operator ++(C c) { return c; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.IncrementOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedCompoundAssignment() { var text = @" class C { public static C operator +(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); /*<bind>*/c1 += c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } private void CheckOperatorSemanticInfo(string text, string operatorName) { var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operatorSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>(operatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); var method = (IMethodSymbol)symbolInfo.Symbol; var returnType = method.ReturnType; var typeInfo = model.GetTypeInfo(expr); Assert.Equal(returnType, typeInfo.Type); Assert.Equal(returnType, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.False(model.GetConstantValue(expr).HasValue); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailure() { var text = @" struct S { public static explicit operator S(string s) { return default(S); } public static explicit operator S(System.Text.StringBuilder s) { return default(S); } static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(conversions, EqualityComparer<ISymbol>.Default)); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailureEmpty() { var text = @" struct S { static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversions.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit UnaryOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class UnaryOperator op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } // Differs only by return type .method public hidebysig specialname static string op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { UnaryOperator u1 = new UnaryOperator(); UnaryOperator u2 = /*<bind>*/+u1/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("UnaryOperator").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit IncrementOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class IncrementOperator op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname static string op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { IncrementOperator i1 = new IncrementOperator(); IncrementOperator i2 = /*<bind>*/i1++/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IncrementOperator").GetMembers(WellKnownMemberNames.IncrementOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.IncrementOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(529158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529158")] [Fact] public void MethodGroupForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, int i) { return c1; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName).Cast<IMethodSymbol>(); var operatorSymbol = operators.Where(method => method.Parameters[0].Type.Equals(method.Parameters[1].Type, SymbolEqualityComparer.ConsiderEverything)).Single(); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); // NOTE: This check captures, rather than enforces, the current behavior (i.e. feel free to change it). var memberGroup = model.GetMemberGroup(expr); Assert.Equal(0, memberGroup.Length); } [Fact] public void CacheDuplicates() { var text = @" class C { static void Main() { long l = /*<bind>*/(long)1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); bool sawWrongConversionKind = false; ThreadStart ts = () => sawWrongConversionKind |= ConversionKind.Identity != model.GetConversion(expr).Kind; Thread[] threads = new Thread[4]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(ts); } foreach (Thread t in threads) { t.Start(); } foreach (Thread t in threads) { t.Join(); } Assert.False(sawWrongConversionKind); } [WorkItem(543674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543674")] [Fact()] public void SemanticInfo_NormalVsLiftedUserDefinedImplicitConversion() { string text = @" using System; struct G { } struct L { public static implicit operator G(L l) { return default(G); } } class Z { public static void Main() { MNG(/*<bind>*/default(L)/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); // Here we have a situation where Roslyn deliberately violates the specification in order // to be compatible with the native compiler. // // The specification states that there are two applicable candidates: We can use // the "lifted" operator from L? to G?, or we can use the unlifted operator // from L to G, and then convert the G that comes out the back end to G?. // The specification says that the second conversion is the better conversion. // Therefore, the conversion on the "front end" should be an identity conversion, // and the conversion on the "back end" of the user-defined conversion should // be an implicit nullable conversion. // // This is not at all what the native compiler does, and we match the native // compiler behavior. The native compiler says that there is a "half lifted" // conversion from L-->G?, and that this is the winner. Therefore the conversion // "on the back end" of the user-defined conversion is in fact an *identity* // conversion, even though obviously we are going to have to // do code generation as though it was an implicit nullable conversion. Assert.Equal(ConversionKind.Identity, conversion.UserDefinedFromConversion.Kind); Assert.Equal(ConversionKind.Identity, conversion.UserDefinedToConversion.Kind); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [WorkItem(543715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543715")] [Fact] public void SemanticInfo_NormalVsLiftedUserDefinedConversion_ImplicitConversion() { string text = @" using System; struct G {} struct M { public static implicit operator G(M m) { System.Console.WriteLine(1); return default(G); } public static implicit operator G(M? m) {System.Console.WriteLine(2); return default(G); } } class Z { public static void Main() { M? m = new M(); MNG(/*<bind>*/m/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion.Kind); // Dev10 violates the spec for finding the most specific operator for an implicit user-defined conversion. // SPEC: • Find the most specific conversion operator: // SPEC: (a) If U contains exactly one user-defined conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (b) Otherwise, if U contains exactly one lifted conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (c) Otherwise, the conversion is ambiguous and a compile-time error occurs. // In this test we try to classify conversion from M? to G?. // 1) Classify conversion establishes that SX: M? and TX: G?. // 2) Most specific conversion operator from M? to G?: // (a) does not hold here as neither of the implicit operators convert from M? to G? // (b) does hold here as the lifted form of "implicit operator G(M m)" converts from M? to G? // Hence "operator G(M m)" must be chosen in lifted form, but Dev10 chooses "G M.op_Implicit(System.Nullable<M> m)" in normal form. // We may want to maintain compatibility with Dev10. Assert.Equal("G M.op_Implicit(M? m)", conversion.MethodSymbol.ToTestDisplayString()); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [Fact] public void AmbiguousImplicitConversionOverloadResolution1() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void M(A a) { } static void M(object o) { } static void Main() { B b = new B(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (26,21): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void Test.M(A a)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("A", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.ImplicitUserDefined, argConversion.Kind); Assert.False(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void AmbiguousImplicitConversionOverloadResolution2() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void M(A a) { } static void M<T>(T t) { } static void Main() { B<A> b = new B<A>(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); // since no conversion is performed, the ambiguity doesn't matter var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void C.M<B<A>>(B<A> t)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B<A>", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("B<A>", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.Identity, argConversion.Kind); Assert.True(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void DefaultParameterLocalScope() { var source = @" public class A { static void Main(string[] args, int a = /*<bind>*/System/*</bind>*/.) { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("System", expr.ToString()); var info = model.GetSemanticInfoSummary(expr); //Shouldn't throw/assert Assert.Equal(SymbolKind.Namespace, info.Symbol.Kind); } [Fact] public void PinvokeSemanticModel() { var source = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""user32.dll"", CharSet = CharSet.Unicode, ExactSpelling = false, EntryPoint = ""MessageBox"")] public static extern int MessageBox(IntPtr hwnd, string t, string c, UInt32 t2); static void Main() { /*<bind>*/MessageBox(IntPtr.Zero, """", """", 1)/*</bind>*/; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("MessageBox(IntPtr.Zero, \"\", \"\", 1)", expr.ToString()); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("C.MessageBox(System.IntPtr, string, string, uint)", symbolInfo.Symbol.ToDisplayString()); var argTypeInfo = model.GetTypeInfo(expr.ArgumentList.Arguments.First().Expression); Assert.Equal("System.IntPtr", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("System.IntPtr", argTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void ImplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = 1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var conv = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, conv.Kind); } [Fact] public void ImplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Int64, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, castConversion.Kind); } [Fact] public void ExplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = (object)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Object, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, castConversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(literal, castTypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); } [Fact] public void ExplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (object)(long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast1 = (CastExpressionSyntax)literal.Parent; var cast1TypeInfo = model.GetTypeInfo(cast1); var cast1Conversion = model.GetConversion(cast1); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast1Conversion.Kind); // Note that this reflects the hypothetical conversion, not the cast in the code. Assert.Equal(ConversionKind.ImplicitNumeric, model.ClassifyConversion(literal, cast1TypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); var cast2 = (CastExpressionSyntax)cast1.Parent; var cast2TypeInfo = model.GetTypeInfo(cast2); var cast2Conversion = model.GetConversion(cast2); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast2Conversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(cast1, cast2TypeInfo.Type).Kind); CheckIsAssignableTo(model, cast1); } [WorkItem(545136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545136")] [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact()] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins. public void SpecialTypeInSourceAndMetadata() { var text = @" using System; namespace System { public struct Void { static void Main() { System./*<bind>*/Void/*</bind>*/.Equals(1, 1); } } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.Void", symbolInfo.Symbol.ToString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup1() { var text = @" using System; class C { static void M() { int here; } } "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup2() { var text = @" using System; class C { static void M() { int here; } static void M(int x) { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent1() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/ "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent2() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/[] "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup1() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = (Compilation)CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("IA").GetMember<IPropertySymbol>("P"), info.Symbol); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object Property P(x As Object, y As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } // There is no test analogous to UnambiguousMethodGroupWithoutBoundParent1 because // a.P does not yield a bound property group - it yields a bound indexer access // (i.e. it doesn't actually hit the code path that formerly contained the assert). //[WorkItem(15177)] //[Fact] //public void UnambiguousPropertyGroupWithoutBoundParent1() [WorkItem(546117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546117")] [ClrOnlyFact] public void UnambiguousPropertyGroupWithoutBoundParent2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { /*<bind>*/a.P/*</bind>*/[] "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.QualifiedName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544648")] [Fact] public void SpeculativelyBindExtensionMethod() { var source = @" using System; using System.Collections.Generic; using System.Reflection; static class Program { static void Main() { FieldInfo[] fields = typeof(Exception).GetFields(); Console.WriteLine(/*<bind>*/fields.Any((Func<FieldInfo, bool>)(field => field.IsStatic))/*</bind>*/); } static bool Any<T>(this IEnumerable<T> s, Func<T, bool> predicate) { return false; } static bool Any<T>(this ICollection<T> s, Func<T, bool> predicate) { return true; } } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var originalSyntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.InvocationExpression, originalSyntax.Kind()); var info1 = model.GetSymbolInfo(originalSyntax); var method1 = info1.Symbol as IMethodSymbol; Assert.NotNull(method1); Assert.Equal("System.Boolean System.Collections.Generic.ICollection<System.Reflection.FieldInfo>.Any<System.Reflection.FieldInfo>(System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", method1.ToTestDisplayString()); Assert.Same(method1.ReducedFrom.TypeParameters[0], method1.TypeParameters[0].ReducedFrom); Assert.Null(method1.ReducedFrom.TypeParameters[0].ReducedFrom); Assert.Equal("System.Boolean Program.Any<T>(this System.Collections.Generic.ICollection<T> s, System.Func<T, System.Boolean> predicate)", method1.ReducedFrom.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.ICollection<System.Reflection.FieldInfo>", method1.ReceiverType.ToTestDisplayString()); Assert.Equal("System.Reflection.FieldInfo", method1.GetTypeInferredDuringReduction(method1.ReducedFrom.TypeParameters[0]).ToTestDisplayString()); Assert.Throws<InvalidOperationException>(() => method1.ReducedFrom.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentNullException>(() => method1.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentException>(() => method1.GetTypeInferredDuringReduction( comp.Assembly.GlobalNamespace.GetMember<INamedTypeSymbol>("Program").GetMembers("Any"). Where((m) => (object)m != (object)method1.ReducedFrom).Cast<IMethodSymbol>().Single().TypeParameters[0])); Assert.Equal("Any", method1.Name); var reducedFrom1 = method1.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom1); Assert.Equal("System.Boolean Program.Any<System.Reflection.FieldInfo>(this System.Collections.Generic.ICollection<System.Reflection.FieldInfo> s, System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", reducedFrom1.ToTestDisplayString()); Assert.Equal("Program", reducedFrom1.ReceiverType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom1.Parameters[0].Type.OriginalDefinition).SpecialType); var speculativeSyntax = SyntaxFactory.ParseExpression("fields.Any((field => field.IsStatic))"); //cast removed Assert.Equal(SyntaxKind.InvocationExpression, speculativeSyntax.Kind()); var info2 = model.GetSpeculativeSymbolInfo(originalSyntax.SpanStart, speculativeSyntax, SpeculativeBindingOption.BindAsExpression); var method2 = info2.Symbol as IMethodSymbol; Assert.NotNull(method2); Assert.Equal("Any", method2.Name); var reducedFrom2 = method2.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom2); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom2.Parameters[0].Type.OriginalDefinition).SpecialType); Assert.Equal(reducedFrom1, reducedFrom2); Assert.Equal(method1, method2); } /// <summary> /// This test reproduces the issue we were seeing in DevDiv #13366: LocalSymbol.SetType was asserting /// because it was set to IEnumerable&lt;int&gt; before binding the declaration of x but to an error /// type after binding the declaration of x. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding1() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info0 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info0.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info0.Symbol).TypeArguments.Single().SpecialType); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } /// <summary> /// This test reverses the order of statement binding from NameConflictDuringLambdaBinding2 to confirm that /// the results are the same. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding2() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } [WorkItem(546263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546263")] [Fact] public void SpeculativeSymbolInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeSymbolInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Null(info.Symbol); } [WorkItem(530313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530313")] [Fact] public void SpeculativeTypeInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Equal(TypeInfo.None, info); } [WorkItem(546266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546266")] [Fact] public void SpeculativeTypeInfoForGenericNameSyntaxWithinTypeOfInsideAnonMethod() { var text = @" delegate void Del(); class C { public void M1() { Del d = delegate () { var v1 = typeof(S<,,,>); }; } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("S<,,,>", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<GenericNameSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void SemanticInfoForOmittedTypeArgumentInIncompleteMember() { var text = @" class Test { C<> "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSemanticInfoSummary(syntax); Assert.Null(info.Alias); Assert.Equal(CandidateReason.None, info.CandidateReason); Assert.True(info.CandidateSymbols.IsEmpty); Assert.False(info.ConstantValue.HasValue); Assert.Null(info.ConvertedType); Assert.Equal(Conversion.Identity, info.ImplicitConversion); Assert.False(info.IsCompileTimeConstant); Assert.True(info.MemberGroup.IsEmpty); Assert.True(info.MethodGroup.IsEmpty); Assert.Null(info.Symbol); Assert.Null(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void CollectionInitializerSpeculativeInfo() { var text = @" class Test { } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var speculativeSyntax = SyntaxFactory.ParseExpression("new List { 1, 2 }"); var initializerSyntax = speculativeSyntax.DescendantNodesAndSelf().OfType<InitializerExpressionSyntax>().Single(); var symbolInfo = model.GetSpeculativeSymbolInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); var typeInfo = model.GetSpeculativeTypeInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(TypeInfo.None, typeInfo); } [WorkItem(531362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531362")] [Fact] public void DelegateElementAccess() { var text = @" class C { void M(bool b) { System.Action o = delegate { if (b) { } } [1]; } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (6,27): error CS0021: Cannot apply indexing with [] to an expression of type 'anonymous method' // System.Action o = delegate { if (b) { } } [1]; Diagnostic(ErrorCode.ERR_BadIndexLHS, "delegate { if (b) { } } [1]").WithArguments("anonymous method")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last(id => id.Identifier.ValueText == "b"); var info = model.GetSymbolInfo(syntax); } [Fact] public void EnumBitwiseComplement() { var text = @" using System; enum Color { Red, Green, Blue } class C { static void Main() { Func<Color, Color> f2 = x => /*<bind>*/~x/*</bind>*/; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(syntax); var conv = model.GetConversion(syntax); Assert.Equal(TypeKind.Enum, info.Type.TypeKind); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(531534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531534")] [Fact] public void LambdaOutsideMemberModel() { var text = @" int P { badAccessorName { M(env => env); "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last(); var symbol = model.GetDeclaredSymbol(syntax); // Doesn't assert. Assert.Null(symbol); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void MemberOfInaccessibleType() { var text = @" class A { private class Nested { public class Another { } } } public class B : A { public Nested.Another a; } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var classAnother = classNested.GetMember<INamedTypeSymbol>("Another"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var fieldSyntax = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single(); var qualifiedSyntax = (QualifiedNameSyntax)fieldSyntax.Declaration.Type; var leftSyntax = qualifiedSyntax.Left; var rightSyntax = qualifiedSyntax.Right; var leftInfo = model.GetSymbolInfo(leftSyntax); Assert.Equal(CandidateReason.Inaccessible, leftInfo.CandidateReason); Assert.Equal(classNested, leftInfo.CandidateSymbols.Single()); var rightInfo = model.GetSymbolInfo(rightSyntax); Assert.Equal(CandidateReason.Inaccessible, rightInfo.CandidateReason); Assert.Equal(classAnother, rightInfo.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0060: Inconsistent accessibility: base type 'A' is less accessible than class 'B' // public class B : A Diagnostic(ErrorCode.ERR_BadVisBaseClass, "B").WithArguments("B", "A"), // (14,12): error CS0122: 'A.Nested' is inaccessible due to its protection level // public Nested.Another a; Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void NotReferencableMemberOfInaccessibleType() { var text = @" class A { private class Nested { public int P { get; set; } } } class B : A { int Test(Nested nested) { return nested.get_P(); } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var propertyP = classNested.GetMember<IPropertySymbol>("P"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccessSyntax = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessSyntax); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); Assert.Equal(propertyP.GetMethod, info.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0122: 'A.Nested' is inaccessible due to its protection level // int Test(Nested nested) Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested"), // (14,23): error CS0571: 'A.Nested.P.get': cannot explicitly call operator or accessor // return nested.get_P(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.Nested.P.get") ); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void AccessibleMemberOfInaccessibleType() { var text = @" public class A { private class Nested { } } public class B : A { void Test() { Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodAccessSyntax = (MemberAccessExpressionSyntax)callSyntax.Expression; var nestedTypeAccessSyntax = methodAccessSyntax.Expression; var typeInfo = model.GetSymbolInfo(nestedTypeAccessSyntax); Assert.Equal(CandidateReason.Inaccessible, typeInfo.CandidateReason); Assert.Equal(classNested, typeInfo.CandidateSymbols.Single()); var methodInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals), methodInfo.Symbol); compilation.VerifyDiagnostics( // (13,9): error CS0122: 'A.Nested' is inaccessible due to its protection level // Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols1() { var text = @" class C { public override int GetHashCode() { return 0; } } struct S { public override int GetHashCode() { return 0; } } class Test { int M(C c) { return c.GetHashCode } int M(S s) { return s.GetHashCode } } "; var compilation = CreateCompilation(text); var global = compilation.GlobalNamespace; var classType = global.GetMember<NamedTypeSymbol>("C"); var structType = global.GetMember<NamedTypeSymbol>("S"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccesses = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, memberAccesses.Length); var classMemberAccess = memberAccesses[0]; var structMemberAccess = memberAccesses[1]; var classInfo = model.GetSymbolInfo(classMemberAccess); var structInfo = model.GetSymbolInfo(structMemberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, classInfo.CandidateReason); Assert.Equal("System.Int32 C.GetHashCode()", classInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, structInfo.CandidateReason); Assert.Equal("System.Int32 S.GetHashCode()", structInfo.CandidateSymbols.Single().ToTestDisplayString()); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols2() { var text = @" class A { public virtual void M() { } } class B : A { public override void M() { } } class C : B { public override void M() { } } class Program { static void Main(string[] args) { C c = new C(); c.M } } "; var compilation = CreateCompilation(text); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal("void C.M()", info.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T>(T t, C c) where T : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter2() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T, U>(T t, C c) where T : U where U : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(652583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652583")] public void ParameterDefaultValueWithoutParameter() { var source = @" class A { protected void Goo(bool b, = true "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var trueLiteral = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.TrueLiteralExpression, trueLiteral.Kind()); model.GetSymbolInfo(trueLiteral); var parameterSyntax = trueLiteral.FirstAncestorOrSelf<ParameterSyntax>(); Assert.Equal(SyntaxKind.Parameter, parameterSyntax.Kind()); model.GetDeclaredSymbol(parameterSyntax); } [Fact] [WorkItem(530791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530791")] public void Repro530791() { var source = @" class Program { static void Main(string[] args) { Test test = new Test(() => { return null; }); } } class Test { } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(lambdaSyntax); var lambda = (IMethodSymbol)symbolInfo.Symbol; Assert.False(lambda.ReturnsVoid); Assert.Equal(SymbolKind.ErrorType, lambda.ReturnType.Kind); } [Fact] public void InvocationInLocalDeclarationInLambdaInConstructorInitializer() { var source = @" using System; public class C { public int M() { return null; } } public class Test { public Test() : this(c => { int i = c.M(); return i; }) { } public Test(Func<C, int> f) { } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(syntax); var methodSymbol = (IMethodSymbol)symbolInfo.Symbol; Assert.False(methodSymbol.ReturnsVoid); } [Fact] [WorkItem(654753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/654753")] public void Repro654753() { var source = @" using System; using System.Collections.Generic; using System.Linq; public class C { private readonly C Instance = new C(); bool M(IDisposable d) { using(d) { bool any = this.Instance.GetList().OfType<D>().Any(); return any; } } IEnumerable<C> GetList() { return null; } } public class D : C { } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("this", StringComparison.Ordinal); var statement = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var newSyntax = SyntaxFactory.ParseExpression("Instance.GetList().OfType<D>().Any()"); var newStatement = statement.ReplaceNode(statement.Declaration.Variables[0].Initializer.Value, newSyntax); newSyntax = newStatement.Declaration.Variables[0].Initializer.Value; SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(position, newStatement, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var newSyntaxMemberAccess = newSyntax.DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>(). Single(e => e.ToString() == "Instance.GetList().OfType<D>"); speculativeModel.GetTypeInfo(newSyntaxMemberAccess); } [Fact] [WorkItem(750557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750557")] public void MethodGroupFromMetadata() { var source = @" class Goo { delegate int D(int i); void M() { var v = ((D)(x => x)).Equals is bool; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("Equals", StringComparison.Ordinal); var equalsToken = tree.GetRoot().FindToken(position); var equalsNode = equalsToken.Parent; var symbolInfo = model.GetSymbolInfo(equalsNode); //note that we don't guarantee what symbol will come back on a method group in an is expression. Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.Length > 0); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForDefinedSymbol() { string sourceCode = @" #define X #if X //bind #define Z #endif #if Z //bind #endif // broken code cases #define A #if A + 1 //bind #endif #define B = 0 #if B //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A + 1 //bind"); Assert.Equal("A", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.Equal("B", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); Assert.True(symbolInfo.Symbol.Equals(symbolInfo.Symbol)); Assert.False(symbolInfo.Symbol.Equals(null)); PreprocessingSymbolInfo symbolInfo2 = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.NotSame(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol.GetHashCode(), symbolInfo2.Symbol.GetHashCode()); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForUndefinedSymbol() { string sourceCode = @" #define X #undef X #if X //bind #endif #if x //bind #endif #if Y //bind #define Z #endif #if Z //bind #endif // Not in preprocessor trivia #define A public class T { public int Goo(int A) { return A; //bind } } "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "x //bind"); Assert.Equal("x", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Y //bind"); Assert.Equal("Y", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A; //bind"); Assert.Null(symbolInfo.Symbol); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304"), WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void GetPreprocessingSymbolInfoForSymbolDefinedLaterInSource() { string sourceCode = @" #if Z //bind #endif #define Z "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_01() { string sourceCode = @" #define Z #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_02() { string sourceCode = @" #if true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_03() { string sourceCode = @" #if false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_04() { string sourceCode = @" #if true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_05() { string sourceCode = @" #if false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_06() { string sourceCode = @" #if true #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_07() { string sourceCode = @" #if false #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_08() { string sourceCode = @" #if true #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_09() { string sourceCode = @" #if false #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_10() { string sourceCode = @" #if true #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_11() { string sourceCode = @" #if false #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_12() { string sourceCode = @" #if false #elif false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_13() { string sourceCode = @" #if true #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_14() { string sourceCode = @" #if true #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_15() { string sourceCode = @" #if false #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_16() { string sourceCode = @" #if false #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_17() { string sourceCode = @" #if false #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_18() { string sourceCode = @" #if false #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_19() { string sourceCode = @" #if true #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_20() { string sourceCode = @" #if true #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_21() { string sourceCode = @" #if true #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_22() { string sourceCode = @" #if false #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [WorkItem(835391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835391")] [Fact] public void ConstructedErrorTypeValidation() { var text = @"class C1 : E1 { } class C2<T> : E2<T> { }"; var compilation = (Compilation)CreateCompilation(text); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); // Non-generic type. var type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[0]); Assert.False(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Non-generic error type. type = type.BaseType; Assert.False(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Generic type. type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[1]); Assert.True(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type // Generic error type. type = type.BaseType.ConstructedFrom; Assert.True(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type } [Fact] [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] public void NestedLambdaErrorRecovery() { var source = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main() { Task<IEnumerable<Task<A>>> teta = null; teta.ContinueWith(tasks => { var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. list.ToString(); }); } static B X(int x) { return null; } class A { } class B { } } "; for (int i = 0; i < 10; i++) // Ten runs to ensure consistency. { var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (13,51): error CS1503: Argument 1: cannot convert from 'Program.A' to 'int' // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_BadArgType, "t.Result").WithArguments("1", "Program.A", "int").WithLocation(13, 51), // (13,30): error CS1061: 'System.Threading.Tasks.Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?) // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Result").WithArguments("System.Threading.Tasks.Task", "Result").WithLocation(13, 30)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var invocationInfo = model.GetSymbolInfo(invocationSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, invocationInfo.CandidateReason); Assert.Null(invocationInfo.Symbol); Assert.NotEqual(0, invocationInfo.CandidateSymbols.Length); var parameterSyntax = invocationSyntax.DescendantNodes().OfType<ParameterSyntax>().First(); var parameterSymbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal("System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<Program.A>>>", parameterSymbol.Type.ToTestDisplayString()); } } [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [WorkItem(854548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854548")] [Fact] public void SemanticModelLambdaErrorRecovery() { var source = @" using System; class Program { static void Main() { M(() => 1); // Neither overload wins. } static void M(Func<string> a) { } static void M(Func<char> a) { } } "; { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); } { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversion = model.ClassifyConversion(lambdaSyntax, otherFuncType); CheckIsAssignableTo(model, lambdaSyntax); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); // Not affected by call to ClassifyConversion. } } [Fact] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] public void ClassifyConversionOnNull() { var source = @" class Program { static void Main() { M(null); // Ambiguous. } static void M(A a) { } static void M(B b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var nullSyntax = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var conversion = model.ClassifyConversion(nullSyntax, typeC); CheckIsAssignableTo(model, nullSyntax); Assert.Equal(ConversionKind.ImplicitReference, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnLambda() { var source = @" using System; class Program { static void Main() { M(() => null); } static void M(Func<A> a) { } } class A { } class B { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeB = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("B"); var typeFuncB = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeB); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncB); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousLambda() { var source = @" using System; class Program { static void Main() { M(() => null); // Ambiguous. } static void M(Func<A> a) { } static void M(Func<B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(System.Func<A>)' and 'Program.M(System.Func<B>)' // M(() => null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(System.Func<A>)", "Program.M(System.Func<B>)").WithLocation(8, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var typeFuncC = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeC); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncC); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousMethodGroup() { var source = @" using System; class Base<T> { public A N(T t) { throw null; } public B N(int t) { throw null; } } class Derived : Base<int> { void Test() { M(N); // Ambiguous. } static void M(Func<int, A> a) { } static void M(Func<int, B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Derived.M(System.Func<int, A>)' and 'Derived.M(System.Func<int, B>)' // M(N); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Derived.M(System.Func<int, A>)", "Derived.M(System.Func<int, B>)").WithLocation(14, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var methodGroupSyntax = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>().Single().Expression; var global = comp.GlobalNamespace; var typeA = global.GetMember<INamedTypeSymbol>("A"); var typeB = global.GetMember<INamedTypeSymbol>("B"); var typeC = global.GetMember<INamedTypeSymbol>("C"); var typeInt = comp.GetSpecialType(SpecialType.System_Int32); var typeFunc = comp.GetWellKnownType(WellKnownType.System_Func_T2); var typeFuncA = typeFunc.Construct(typeInt, typeA); var typeFuncB = typeFunc.Construct(typeInt, typeB); var typeFuncC = typeFunc.Construct(typeInt, typeC); var conversionA = model.ClassifyConversion(methodGroupSyntax, typeFuncA); CheckIsAssignableTo(model, methodGroupSyntax); Assert.Equal(ConversionKind.MethodGroup, conversionA.Kind); var conversionB = model.ClassifyConversion(methodGroupSyntax, typeFuncB); Assert.Equal(ConversionKind.MethodGroup, conversionB.Kind); var conversionC = model.ClassifyConversion(methodGroupSyntax, typeFuncC); Assert.Equal(ConversionKind.NoConversion, conversionC.Kind); } [WorkItem(872064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872064")] [Fact] public void PartialMethodImplementationDiagnostics() { var file1 = @" namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m); } } "; var file2 = @" namespace ConsoleApplication1 { partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m) { c = new MyUndefinedMethod(23, true); } } } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var comp = CreateCompilation(new[] { tree1, tree2 }); var model = comp.GetSemanticModel(tree2); var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(2, errs.Count()); } [Fact] public void PartialTypeDiagnostics_StaticConstructors() { var file1 = @" partial class C { static C() {} } "; var file2 = @" partial class C { static C() {} } "; var file3 = @" partial class C { static C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); model3.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").StaticConstructors.Length); } [Fact] public void PartialTypeDiagnostics_Constructors() { var file1 = @" partial class C { C() {} } "; var file2 = @" partial class C { C() {} } "; var file3 = @" partial class C { C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); model3.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Length); } [WorkItem(1076661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1076661")] [Fact] public void Bug1076661() { const string source = @" using X = System.Collections.Generic.List<dynamic>; class Test { void Goo(ref X. x) { } }"; var comp = CreateCompilation(source); var diag = comp.GetDiagnostics(); } [Fact] public void QueryClauseInBadStatement_Catch() { var source = @"using System; class C { static void F(object[] c) { catch (Exception) when (from o in c where true) { } } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(); var expr = tokens.Single(t => t.Kind() == SyntaxKind.TrueKeyword).Parent; Assert.Null(model.GetSymbolInfo(expr).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(expr).Type.SpecialType); } [Fact] public void GetSpecialType_ThrowsOnLessThanZero() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = (SpecialType)(-1); var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] public void GetSpecialType_ThrowsOnGreaterThanCount() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = SpecialType.Count + 1; var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] [WorkItem(34984, "https://github.com/dotnet/roslyn/issues/34984")] public void ConversionIsExplicit_UnsetConversionKind() { var source = @"class C1 { } class C2 { public void M() { var c = new C1(); foreach (string item in c.Items) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var foreachSyntaxNode = root.DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var foreachSymbolInfo = model.GetForEachStatementInfo(foreachSyntaxNode); Assert.Equal(Conversion.UnsetConversion, foreachSymbolInfo.CurrentConversion); Assert.True(foreachSymbolInfo.CurrentConversion.Exists); Assert.False(foreachSymbolInfo.CurrentConversion.IsImplicit); } [Fact, WorkItem(29933, "https://github.com/dotnet/roslyn/issues/29933")] public void SpeculativelyBindBaseInXmlDoc() { var text = @" class C { /// <summary> </summary> static void M() { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf(">", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression("base"); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); } [Fact] [WorkItem(42840, "https://github.com/dotnet/roslyn/issues/42840")] public void DuplicateTypeArgument() { var source = @"class A<T> { } class B<T, U, U> where T : A<U> where U : class { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,15): error CS0692: Duplicate type parameter 'U' // class B<T, U, U> Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 15), // (5,17): error CS0229: Ambiguity between 'U' and 'U' // where T : A<U> Diagnostic(ErrorCode.ERR_AmbigMember, "U").WithArguments("U", "U").WithLocation(5, 17)); comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var typeParameters = tree.GetRoot().DescendantNodes().OfType<TypeParameterSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 1]); Assert.False(symbol.IsReferenceType); symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 2]); Assert.True(symbol.IsReferenceType); } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/MakeTypeAbstract/CSharpMakeTypeAbstractCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.MakeTypeAbstract; namespace Microsoft.CodeAnalysis.CSharp.MakeTypeAbstract { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeTypeAbstract), Shared] internal sealed class CSharpMakeTypeAbstractCodeFixProvider : AbstractMakeTypeAbstractCodeFixProvider<TypeDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpMakeTypeAbstractCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( "CS0513" // 'C.M()' is abstract but it is contained in non-abstract type 'C' ); protected override bool IsValidRefactoringContext(SyntaxNode? node, [NotNullWhen(true)] out TypeDeclarationSyntax? typeDeclaration) { switch (node) { case MethodDeclarationSyntax method: if (method.Body != null || method.ExpressionBody != null) { typeDeclaration = null; return false; } break; case AccessorDeclarationSyntax accessor: if (accessor.Body != null || accessor.ExpressionBody != null) { typeDeclaration = null; return false; } break; default: typeDeclaration = null; return false; } var enclosingType = node.FirstAncestorOrSelf<TypeDeclarationSyntax>(); if ((enclosingType.IsKind(SyntaxKind.ClassDeclaration) || enclosingType.IsKind(SyntaxKind.RecordDeclaration)) && !enclosingType.Modifiers.Any(SyntaxKind.AbstractKeyword) && !enclosingType.Modifiers.Any(SyntaxKind.StaticKeyword)) { typeDeclaration = enclosingType; return true; } typeDeclaration = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.MakeTypeAbstract; namespace Microsoft.CodeAnalysis.CSharp.MakeTypeAbstract { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeTypeAbstract), Shared] internal sealed class CSharpMakeTypeAbstractCodeFixProvider : AbstractMakeTypeAbstractCodeFixProvider<TypeDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpMakeTypeAbstractCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( "CS0513" // 'C.M()' is abstract but it is contained in non-abstract type 'C' ); protected override bool IsValidRefactoringContext(SyntaxNode? node, [NotNullWhen(true)] out TypeDeclarationSyntax? typeDeclaration) { switch (node) { case MethodDeclarationSyntax method: if (method.Body != null || method.ExpressionBody != null) { typeDeclaration = null; return false; } break; case AccessorDeclarationSyntax accessor: if (accessor.Body != null || accessor.ExpressionBody != null) { typeDeclaration = null; return false; } break; default: typeDeclaration = null; return false; } var enclosingType = node.FirstAncestorOrSelf<TypeDeclarationSyntax>(); if ((enclosingType.IsKind(SyntaxKind.ClassDeclaration) || enclosingType.IsKind(SyntaxKind.RecordDeclaration)) && !enclosingType.Modifiers.Any(SyntaxKind.AbstractKeyword) && !enclosingType.Modifiers.Any(SyntaxKind.StaticKeyword)) { typeDeclaration = enclosingType; return true; } typeDeclaration = null; return false; } } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_ExternalErrorReporting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private ProjectExternalErrorReporter GetExternalErrorReporter() { var errorReporter = _externalErrorReporter.Value; if (errorReporter == null) { throw new InvalidOperationException("The language of the project doesn't support external errors."); } return errorReporter; } public int ClearAllErrors() => GetExternalErrorReporter().ClearAllErrors(); public int AddNewErrors(IVsEnumExternalErrors pErrors) => GetExternalErrorReporter().AddNewErrors(pErrors); public int GetErrors(out IVsEnumExternalErrors pErrors) => GetExternalErrorReporter().GetErrors(out pErrors); public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) => GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); public int ClearErrors() => GetExternalErrorReporter().ClearErrors(); public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) => GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private ProjectExternalErrorReporter GetExternalErrorReporter() { var errorReporter = _externalErrorReporter.Value; if (errorReporter == null) { throw new InvalidOperationException("The language of the project doesn't support external errors."); } return errorReporter; } public int ClearAllErrors() => GetExternalErrorReporter().ClearAllErrors(); public int AddNewErrors(IVsEnumExternalErrors pErrors) => GetExternalErrorReporter().AddNewErrors(pErrors); public int GetErrors(out IVsEnumExternalErrors pErrors) => GetExternalErrorReporter().GetErrors(out pErrors); public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) => GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); public int ClearErrors() => GetExternalErrorReporter().ClearErrors(); public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) => GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } }
-1
dotnet/roslyn
56,090
Disallow converting a lambda with attributes to an expression tree.
Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
AlekseyTs
"2021-09-01T21:52:53Z"
"2021-09-02T12:51:31Z"
a835dd858e7472a7598e4275ed014a90d13fc0a0
f16180767deec9090bf478a7e0516e92fb3dd723
Disallow converting a lambda with attributes to an expression tree.. Closes #53910. Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpEscapingReducer.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpEscapingReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { } public override SyntaxToken VisitToken(SyntaxToken token) { var newToken = base.VisitToken(token); return SimplifyToken(newToken, s_simplifyIdentifierToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpEscapingReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { } public override SyntaxToken VisitToken(SyntaxToken token) { var newToken = base.VisitToken(token); return SimplifyToken(newToken, s_simplifyIdentifierToken); } } } }
-1